0

我在一个函数中生成一个字典,然后返回这个字典。尽管格式正确,但我似乎无法将返回的 dict 作为字典访问。它仅将数据视为字符串,即我可以打印它但不能打印 d.keys() 或 d。 items() 我到底做错了什么??????

打印为 str() 时的数据

{1:'21490285,214902909',2:'214902910,214902934',3:'214902935,214902959' : '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()
4

2 回答 2

2

您尽早返回一个字符串:

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-03T09:04:47.157 回答
0

我想知道return 'null'应该实现什么。我的猜测是,你偶尔会用错误的参数调用函数并取回这个字符串。

我建议改为抛出异常(raise Exception('Not enough arguments')或类似)或返回空字典。

您还应该了解,repr()因为它为您提供了有关对象的更多信息,从而使调试更加容易。

于 2013-10-03T09:04:02.180 回答