【发布时间】:2013-10-09 21:25:18
【问题描述】:
我在一个函数中生成一个字典,然后返回这个字典。尽管格式正确,但我似乎无法将返回的 dict 作为字典访问。它仅将数据视为字符串,即我可以打印它但不能打印 d.keys() 或 d。 items() 我到底做错了什么??????
打印为 str() 时的数据
{1:'214902885,2: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: '214903110,214903139'}
我尝试打印 d.items() 或 d.keys() 时出错
print bin_mapping.keys()
AttributeError: 'str' 对象没有属性 'keys'
从函数返回字典后,是否必须将其重新定义为字典?我真的很感激一些帮助,因为我非常沮丧:/
谢谢,
这里建议的是代码。我调用的函数是首先返回字典。
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
调用函数并尝试访问字典
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()
【问题讨论】:
-
也许您应该发布返回该数据的函数?以及调用它的代码?
-
我本来打算写的,但是代码很多...可能是截断版本..我会继续写的。
-
检查“null”是否从未返回...
-
Ick,1 个空格缩进?您如何阅读这些东西,更不用说维护它了?
-
谢谢乔治!!我忽略了一个非常简单的错误。非常感谢您的帮助!
标签: python string function dictionary return