user2962024
user2962024

Reputation: 317

Multiply a dictionary value by other in a nested dictionary

Sorry for the long question. I have a dictionary like this in Python 3.2:

d = {'Paul ': [5, Counter({'i': 1, 'in': 1, 't': 1, 'fa': 1, 'cr': 1})],
            'Lisa ': [4, Counter({'f': 3, 'bo': 1})],
            'Tracy ': [6, Counter({'sl': 3, 'fi': 1, 'an': 1, 'piz': 1})],
            'Maria': [2, Counter({'t': 2})]}

I need to multiple each of the Counter values for the first value in the key and append those values to the key:

d2 = {'Paul': [5, {'i': (2, 10), 'in': (4, 20), 't': (3, 15), 'fa': (2, 10), 'cr': (2, 10)})], 
'Lisa': [4, {'f': (3, 12), 'bo': (8, 32)})], 
'Tracy': [6, {'sl': (3, 18), 'fi': (1, 6), 'an': (5, 30), 'piz': (2, 12)})]}

So that I would have, in the nested dictionary, a pair of numbers for each key: the first number would be the value that was originally assigned to that key and the second number would be the result the multiplication of the first number in the dictionary by the key. As seen above, for instance, the key i nested in Paul, has a value 1 in the original file and this same value appended by 10 in the output (10 is the value of the key 'i': 2 multiplied by 5, the first value to the key 'Paul' : 5, Counter({'i':2...). And so on... I have tried transforming it into tuples:

for key, lst in d.items():
    mult[key] = [lst[0], {k: (lst[0], float(v)/lst[0]) for k, v in lst[1].items()}]

But I got the wrong outcome, for instance:

d2 = {'Paul ': [5, {'i': (5, 10), 'in': (5, 20), 't': (5, 15), 'cr: (5, 10}]...

in which the original value attributed to each key is substituted by the first value of the result of the multiplication. I really tried different things to get around this but to no avail. Has anyone a tip on how to solve this. I am learning Python very slowly, and this would be of great help. Thank you!

Upvotes: 0

Views: 842

Answers (1)

poke
poke

Reputation: 387955

{k: (lst[0], float(v)/lst[0]) for k, v in lst[1].items()}

The first value here is lst[0] which is the first value from the dictionary list but not the original value in the counter; that would be v.

Upvotes: 1

Related Questions