Home > database >  How to update values of keys in dictionary in python?
How to update values of keys in dictionary in python?

Time:07-05

I have a list of possible triplets. I ran a sliding window to calculate the possible triplets and store the values in a list. I have also created a dictionary with the possible triplets as "key" and have initiated the values of those keys as "0". I have written a code that runs through the list to first find a triplet, then search whether that triplet is in the dictionary and if it is there then update the value of the specific key.

trip = '1234'
window_size=3
seq_triplet = []
for i in range(len(trip) - window_size   1):
    z = trip[i: i   window_size]
    seq_triplet.append(z)
print(seq_triplet)

The output of the following code is:

['123', '234']

The dictionary that I have is:

triplet_dict = {'111':0,'112':0,'113':0,'114':0,'121':0,'122':0,'123':0,'124':0,
     '131':0,'132':0,'133':0,'134':0,'141':0,'142':0,'143':0,'144':0,'211':0,
     '212':0,'213':0,'214':0,'221':0,'222':0,'223':0,'224':0,'231':0,'232':0,
     '233':0,'234':0,'235':0,'236':0,'237':0,'241':0,'242':0,'243':0,'244':0,
     '311':0,'312':0,'313':0,'314':0,'321':0,'322':0,'323':0,'324':0,'331':0,
     '332':0,'333':0,'334':0,'341':0,'342':0,'343':0,'344':0,'411':0,'412':0,
     '413':0,'414':0,'421':0,'422':0,'423':0,'424':0,'431':0,'432':0,'433':0,
     '434':0,'441':0,'442':0,'443':0,'444':0}

I have written the following code but it seems to fail.

for i in range(len(seq_triplet)):
    if(seq_triplet[i] in triplet_dict):
        seq_triplet[i]  =1

Any idea where I might be going wrong. Any help would be much appreciated. Thanks

CodePudding user response:

You can access the dict directly using the key. No need to get the index and the value from the index.

In [1]: triplet_dict = {'111':0,'112':0,'113':0,'114':0,'121':0,'122':0,'123':0,'124':0,
   ...:      '131':0,'132':0,'133':0,'134':0,'141':0,'142':0,'143':0,'144':0,'211':0,
   ...:      '212':0,'213':0,'214':0,'221':0,'222':0,'223':0,'224':0,'231':0,'232':0,
   ...:      '233':0,'234':0,'235':0,'236':0,'237':0,'241':0,'242':0,'243':0,'244':0,
   ...:      '311':0,'312':0,'313':0,'314':0,'321':0,'322':0,'323':0,'324':0,'331':0,
   ...:      '332':0,'333':0,'334':0,'341':0,'342':0,'343':0,'344':0,'411':0,'412':0,
   ...:      '413':0,'414':0,'421':0,'422':0,'423':0,'424':0,'431':0,'432':0,'433':0,
   ...:      '434':0,'441':0,'442':0,'443':0,'444':0}

In [2]: triplet_dict['111']
Out[2]: 0

In [3]: triplet_dict['111']  = 1

In [4]: triplet_dict['111']
Out[4]: 1

In [5]: seq_triplet = ['123', '234']

In [6]: for each in seq_triplet:
   ...:     triplet_dict[each]  = 7

In [8]: triplet_dict['123']
Out[8]: 7

In [9]: triplet_dict['234']
Out[9]: 7

  • Related