简体   繁体   中英

Locating specific keys and corresponding values in dictionary

I wrote the following piece of code:

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) 

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

The code works as follows:

Enter a 2 AA long seq: VE

result will be = 16/(16+23) = 0.41

How it works: the function searches the dictionary dmm for the key similar to the one entered in input (example taken here 'VE'). It stores its value and then searches for all the key-value pairs that have the 1st letter in common and adds all its values and returns a fraction.

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

What I want: keeping the function intact, I want to have a secondary dictionary that iterates for every key-value pair in the dictionary and stores the fractional values of it in a different dictionary such that:

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

I don't want to remove the print statement as it is the output for my program. I however need the new_dict for further work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM