Reputation: 13
I tried to create for loops for my nested dicts, but they do not work properly. My nested dicts look like that:
mydict = {'a':{'alpha': 2, 'Beta': 6, 'Gamma': 10},
'b' : {'Beta' : 3 , 'Delta': 7, 'Epsilon' : 5},
'c' : {'Epsilon': 4 , 'Zeta' : 1, 'alpha' : 6}}
what I want to do is to define a function which gets a dictionary and a word as arguments. It searches through keys in the inner dictionary for the word. If it finds the word in the keys of inner dictionaries, it gets its value and assigns it to keys of the outer dictionary and returns a new dictionary. In this example, if we search for alpha, the result will be something like that:
dict_alpha = {'a': 2,'b' : 0,'c' : 6}
My codes which have not work look like this:
def counter_finding(corpus, word):
dict_2= {}
for k_1, v_1 in corpus.items():
for k_2, v_2 in v_1.items():
if word in key:
dict_2[k_1] = country_value[v_2]
else:
dict_2[k_1] = 0
return dict_2
Upvotes: 1
Views: 78
Reputation: 359
def counter_finding(dict1, word):
dict_2= {}
for k_1, v_1 in dict1.items():
print (k_1,v_1)
if word in v_1:
dict_2[k_1] = v_1[word]
else:dict_2[k_1] = 0
return dict_2
Upvotes: 0
Reputation: 82765
Using a simple iteration and dict.get
Ex:
d = {'a':{'alpha': 2, 'Beta': 6, 'Gamma': 10},
'b' : {'Beta' : 3 , 'Delta': 7, 'Epsilon' : 5},
'c' : {'Epsilon': 4 , 'Zeta' : 1, 'alpha' : 6}}
key = 'alpha'
res = {}
for k, v in d.items():
res[k] = v.get(key, 0) # .get() with default value 0
print(res)
Output:
{'a': 2, 'b': 0, 'c': 6}
Upvotes: 2