我用函数生成一本字典,然后返回这个字典。我似乎无法将返回的字典作为字典访问,尽管它是正确的格式。它只将数据作为字符串处理(我可以打印它,但不能打印d.keys()或d.items(),我到底做错了什么?)
数据打印为str()时
{1:'214902885,214902909',2:'214902910,214902934',3:'214902935,214902959',4:'214902960,214902984',5:'214902985,214903009',6:'214903010,214903034',7:'214903035,214903059',8:'214903060,214903084',9:'214903085,214903109',10:‘21490310,214903139’}
当我试图打印()或d.keys()时出错
print bin_mapping.keys()AttributeError:'str‘对象没有属性’key‘
一旦从函数中返回了dict,是否必须将其重新定义为字典?我真的很想得到帮助,因为我非常沮丧。
谢谢,
这里建议的是代码..函数,我调用它首先返回字典..
def models2bins_utr(id,type,start,end,strand):
''' chops up utr's into bins for mC analysis'''
# first deal with 5' UTR
feature_len = (int(end) - int(start))+1
bin_len = int(feature_len) /10
if int(feature_len) < 10:
return 'null'
#continue
else:
# now calculate the coordinates for each of the 10 bins
bin_start = start
d_utr_5 = {}
d_utr_3 = {}
for i in range(1,11):
# set 1-9 first, then round up bin# 10 )
if i != 10:
bin_end = (int(bin_start) +int(bin_len)) -1
if str(type) == 'utr_5':
d_utr_5[i] = str(bin_start)+','+str(bin_end)
elif str(type) == 'utr_3':
d_utr_3[i] = str(bin_start)+','+str(bin_end)
else:
pass
#now set new bin_start
bin_start = int(bin_end) + 1
# now round up last bin
else:
bin_end = end
if str(type) == 'utr_5':
d_utr_5[i] = str(bin_start)+','+str(bin_end)
elif str(type) == 'utr_3':
d_utr_3[i] = str(bin_start)+','+str(bin_end)
else:
pass
if str(type) == 'utr_5':
return d_utr_5
elif str(type) == 'utr_3':
return d_utr_3调用函数并尝试访问dict
def main():
# get a list of all the mrnas in the db
mrna_list = get_mrna()
for mrna_id in mrna_list:
print '-----'
print mrna_id
mrna_features = features(mrna_id)
# if feature utr, send to models2bins_utr and return dict
for feature in mrna_features:
id = feature[0]
type = feature[1]
start = feature[2]
end = feature[3]
assembly = feature[4]
strand = feature[5]
if str(type) == 'utr_5' or str(type) == 'utr_3':
bin_mapping = models2bins_utr(id,type,start,end,strand)
print bin_mapping
print bin_mapping.keys()发布于 2013-10-03 09:04:47
您可以在前面返回一个字符串:
bin_len = int(feature_len) /10
if int(feature_len) < 10:
return 'null'也许您想在这里引发一个异常,或者至少返回一个空字典或使用None作为一个标志值。
如果使用None,请对其进行测试:
bin_mapping = models2bins_utr(id,type,start,end,strand)
if bin_mapping is not None:
# you got a dictionary.发布于 2013-10-03 09:04:02
我想知道return 'null'应该实现什么。我的猜测是,偶尔使用错误的参数调用函数,并将该字符串返回。
我建议抛出一个异常(raise Exception('Not enough arguments')或类似的),或者返回一个空的dict。
您还应该了解repr(),因为它为您提供了有关对象的更多信息,这使得调试变得更加容易。
https://stackoverflow.com/questions/19154806
复制相似问题