Python:字典被func作为字符串返回?我到底做错了什么



>我正在函数中生成一个字典,然后返回这个字典。我似乎无法将返回的字典作为字典访问,尽管它是正确的格式。它仅将数据视为字符串,即我可以打印它但无法打印 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: '214903110,214903139'}

当我尝试打印 d.items(( 或 d.keys(( 时出错

print bin_mapping.keys()
属性

错误:"str"对象没有属性"键">

一旦我从函数返回了字典,我是否必须将其重新定义为字典?我真的很感激一些帮助,因为我非常沮丧:/

谢谢

正如这里建议的那样,这是代码。我正在调用以首先返回字典的函数。

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()

你提前返回一个字符串:

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.

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

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

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

相关内容

最新更新