Skip to content Skip to sidebar Skip to footer

Adding Dictionary Values With The Missing Values In The Keys

I have the following three dictionaries: Mydict = {'(1)': 850.86, '(1, 2)': 1663.5, '(1, 2, 3)': 2381.67, '(1, 3)': 1568.89, '(2)': 812.04,

Solution 1:

The list of numbers sounds like a good idea, but to me it seems it will still require similar amount of (similar) operations as the following solution:

import re

str_pat = re.compile(r'\((.*)\)')

Mynewdict = Mydict
for key in Mynewdict.keys():

    match = (str_pat.findall(key)[0]).split(',')

    # set(list(map(int, match))) in Python 3.X
    to_add = list(set(A.keys()).difference(set(map(int,match))))

    if to_add:
        for kAB in to_add:
            Mynewdict[key] += min(A[kAB],B[kAB])

For each key in Mynewdict this program finds the pattern between the brackets and turns it into a list match split by ,. This list is then compared to list of keys in A.

The comparison goes through sets - the program construct sets from both lists and returns a set difference (also turned into list) into to_add. to_add is hence a list with keys in A that are numbers not present in the compound key in Mynewdict. This assumes that all the keys in B are also present in A. map is used to convert the strings in match to integers (for comparison with keys in A that are integers). To use it in Python 3.X you need to additionally turn the map(int, match) into a list as noted in the comment.

Last part of the program assigns minimum value between A and B for each missing key to the existing value of Mynewdict. Since Mynewdict is initially a copy of Mydict all the final keys and intial values already exist in it so the program does not need to check for key presence or explicitly add the initial values.

To look for keys in Mynewdict that correspond to specific values it seems you actually have to loop through the dictionary:

find_val = round(min(Mynewdict.values()),2)
for key,value in Mynewdict.items():
    if find_val == round(value,2):
        print key, value

What's important here is the rounding. It is necessary since the values in Mynewdict have variable precision that is often longer than the precision of the value you are looking for. In other words without round(value,2) if will evaluate to False in cases where it is actually True.

Post a Comment for "Adding Dictionary Values With The Missing Values In The Keys"