Opticgenius Opticgenius - 2 years ago 118
Python Question

Adding keys to defaultdict(dict)

I have a defaultdict that looks like this:

my_dict = defaultdict(dict)

which will print out:

defaultdict(<class 'dict'>, {})

I also have two lists, which look like this:

list1 = ["W", "IY", "W"]
list2 = ["w", "ee", "w"]

I would like to create a default dict which looks like this:

defaultdict(<class 'dict'>, {'W': {'w': 2}, 'IY': {'ee': 1}}

which has list1 within a dictionary as keys, with the keys as the next list with a separate dictionary, counting the instances of list2 as values.

So far I have this:

from collections import defaultdict

d = defaultdict(dict)

list1 = ["W", "IY", "W"]
list2 = ["w", "ee", "w"]

for char in list1:
d[char] += 1

I know that this is not correct, as the defaultdict(dict) cannot be treated this way. Is there a way a I could do this? Any help would be greatly appreciated :)

Answer Source

EDITED based on the comment on my original answer.

You'll need a mapping of all possible phonemes to all possible spellings (graphemes).

phonemes = {TH : [th], O : [o], OH : [oh, oo]}

for char in set(list1):
    if char not in d:
        d[char] = {char.lower() : {phone : list2.count(phone) for phone in phonemes[char]}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download