在字典中查找特定键和相应的值

时间:2013-03-27 01:19:23

标签: python dictionary

我写了以下代码:

def all_di(fl):
    dmm = {}
    for k in range(2):
        for i in fl:
            for m in range (len(i)-1):
                temp = i[m:m+k+1]
                if temp in dmm:
                    dmm[temp] += 1.0
                else:
                    dmm[temp] = 1.0
##  return dmm
    p = raw_input("Enter a 2 AA long seq:")
    sum = 0
    for x,y in dmm.iteritems():
        if x == p:
            n1 = y
    for l,m in dmm.iteritems():
        if l[0] == p[0]:
            sum = sum + m
    print float(n1)/float(sum)

all_di(inh) 

如果inh = {'VE':16,'GF':19,'VF':23,'GG' :2}

代码的工作原理如下:

Enter a 2 AA long seq: VE

结果将是= 16/(16+23) = 0.41

工作原理:该函数在字典dmm中搜索与input中输入的密钥类似的密钥(此处为'VE'示例)。它存储其值,然后搜索具有共同第一个字母的所有键值对,并添加其所有值并返回分数。

VE = 16
**V**E + **V**F = 39
= 16/39 = 0.41

我想要的是:保持函数不变,我希望有一个辅助字典,它迭代字典中的每个键值对,并将它的小数值存储在不同的字典中,以便:

new_dict = {'VE' : 0.41, 'GF':0.90,'VF':0.51, 'GG': 0.09}

我不想删除print语句,因为它是我程序的输出。但是我需要new_dict才能继续工作。

1 个答案:

答案 0 :(得分:1)

def all_di(fl,p=0):
  dmm = {}
  interactive = p == 0
  if interactive:
    p = raw_input("Enter a 2 AA long seq:")
  if p in fl: 
    numer = fl[p]
    denom = 0.0 
    for t in fl: 
      if t[0] == p[0]:
        denom = denom + fl[t]
  if interactive:
    print numer / denom
  return numer / denom

inh = {'VE':16,'GF':19,'VF':23,'GG' :2} 
all_di(inh)
new_dict =  {x:all_di(inh, x) for x in inh}
print new_dict