Search code examples
pythondictionarytupleslist-comprehensiondictionary-comprehension

Converting a dictionary to a mathematical expression


{'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}},
 'ARE': {'KLP': {'EST': 6}, 'POL': {'WLR': 4}},
 'DOING': {'TIS': {'OIL': 8}},
 'GREAT': {'POL': {'EOL': 6}},
 'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}},
 'KEEP': {'PAR': {'KOM': 8, 'RTW': 6}, 'PIL': {'XCE': 4, 'ACE': 8}},
 'ROCKING': {'OUL': {'AZS': 6, 'RVX': 8}}}

Need to perform a calculation on the numbers in dictionary.

    Eg: {'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}},
 'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}}} for this example the output would be
  • [(8+6)x8]+[(8+4)x(8+6)]
  • [14x8]+[12x14]
  • 112+168
  • 280

Following is the code I tried :

a = [tuple([k]+list(v.keys())+list(j.values())) for k,v in data.items() for i,j in v.items()]

and it gives :

[('YOU', 'HE', 'SLO', 8, 6),
 ('YOU', 'HE', 'SLO', 8),
 ('ARE', 'KLP', 'POL', 6),
 ('ARE', 'KLP', 'POL', 4),
 ('DOING', 'TIS', 8),
 ('GREAT', 'POL', 6),
 ('WORK', 'KOE', 'ROE', 8, 4),
 ('WORK', 'KOE', 'ROE', 8, 6),
 ('KEEP', 'PAR', 'PIL', 8, 6),
 ('KEEP', 'PAR', 'PIL', 4, 8),
 ('ROCKING', 'OUL', 6, 8)]

Solution

  • The rules aren't well-defined, but I'll give it a shot anyway. I am assuming you only want this calculation to apply to keys YOU and WORK in your nested dictionary. I think a list comprehension will get pretty complicated, and it's more readable to work with loops.

    For each key YOU and WORK, I summed up these two innermost sets of values 8+6, 8 for YOU and 8+4, 8+6 for WORK, multiplied these values together 14*8 for YOU and 12*14 for WORK, then added the products together to get the result = 280

    dict_nested = {'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}}, 
    'ARE': {'KLP': {'EST': 6}, 'POL': {'WLR': 4}}, 
    'DOING': {'TIS': {'OIL': 8}}, 
    'GREAT': {'POL': {'EOL': 6}}, 
    'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}}, 
    'KEEP': {'PAR': {'KOM': 8, 'RTW': 6}, 'PIL': {'XCE': 4, 'ACE': 8}}, 
    'ROCKING': {'OUL': {'AZS': 6, 'RVX': 8}}}
    
    keys = ['YOU','WORK']
    result = 0
    for key in keys:
        inner_keys = dict_nested[key].keys()
        # multiply the values together for the first values of the inner key
        inner_product = 1
        for inner_key in inner_keys:
            inner_product *= sum(list(dict_nested[key][inner_key].values()))
            # print(inner_product)
        result += inner_product
    

    Output:

    >>> result
    280