0

I have two dictionaries as:

d={'doc_1': {'hope': 1, 'court': 2}, 'doc_2': {'hope': 1, 'court': 1}, 'doc_3': {'hope': 1, 'mention': 1}}

and

count={'doc_1': 6, 'doc_2': 5, 'doc_3': 12}

All I want to divide the values of nested dictionary of dictionary d with values of dictionary count based on same keys of both dictionaries. Expected output:-

new={{'doc_1': {'hope': 0.16666666, 'court': 0.3333333}, 'doc_2': {'hope': 0.2, 'court': 0.2}, 'doc_3': {'hope': 0.0833333, 'mention': 0.0833333}}. What I did so far:

new={}
for k,v in d.items():
    for p,q in count.items():
        for w,r in v.items():
            if k==p:
                ratio=r/q
                new[k][w]=ratio

That gave me an error!!!

Learner
  • 800
  • 1
  • 8
  • 23

2 Answers2

2

You can use dict comprehension:

from pprint import pprint

d={'doc_1': {'hope': 1, 'court': 2}, 'doc_2': {'hope': 1, 'court': 1}, 'doc_3': {'hope': 1, 'mention': 1}}
count={'doc_1': 6, 'doc_2': 5, 'doc_3': 12}

new_d = {k:{kk:vv/count[k] for kk, vv in v.items()} for k, v in d.items()}

pprint(new_d)

Prints:

{'doc_1': {'court': 0.3333333333333333, 'hope': 0.16666666666666666},
 'doc_2': {'court': 0.2, 'hope': 0.2},
 'doc_3': {'hope': 0.08333333333333333, 'mention': 0.08333333333333333}}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Regarding your code, the error is generated because you are trying to set a new[k][w] while new[k] doesn't exist. To correct this, you should initialize new[k] as an empty dictionary and then fill it :

new={}
for k,v in d.items():
    new[k] = {}
    for p,q in count.items():
        for w,r in v.items():
            if k==p:
                ratio=r/q
                new[k][w]=ratio

Output

{'doc_1': {'hope': 0.16666666666666666, 'court': 0.3333333333333333},
 'doc_2': {'hope': 0.2, 'court': 0.2},
 'doc_3': {'hope': 0.08333333333333333, 'mention': 0.08333333333333333}}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sebastien D
  • 4,369
  • 4
  • 18
  • 46
  • Thanks mentioning the error in my code. Actually, all I want to add nested dictionary in `new` blank dictionary. This is how nested dictionary were created using existing key values? – Learner Jul 08 '19 at 10:15
  • Yes, a nested dictionnary is a dictionary within a dictionary. You might have a look at this nice answer : https://stackoverflow.com/a/16333441/7652544 – Sebastien D Jul 08 '19 at 13:37