Question: 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!!!

Answer: 
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}}

```
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}}

```