Reputation: 210
I have a nested dictionary whose values are all 0. e.g.
dic = {0:{'year': 0, 'drive': 0, 'local': 0,},
1:{'day': 0, 'element': 0, 'party': 0},
2:{'carry': 0}}
I also have a list of words:
wordlist = ['light', 'day', 'year', 'day', 'party', 'care', 'local']
I want to check for each word in the wordlist if it appears in the dictionary, and if it does, append the relative key by 1.
So for the above example I want the following output:
dic = {0:{'year': 1, 'drive': 0, 'local': 1,},
1:{'day': 2, 'element': 0, 'party': 1},
2:{'carry': 0}}
Upvotes: 0
Views: 333
Reputation: 24232
Here is a more efficient solution that iterates only once on the list of names, and once on the nested dict, so it will be O(nb of items of dict + size of list):
from collections import Counter
dic = {0:{'year': 0, 'drive': 0, 'local': 0,},
1:{'day': 0, 'element': 0, 'party': 0},
2:{'carry': 0}}
wordlist = ['light', 'day', 'year', 'day', 'party', 'care', 'local']
word_counts = Counter(wordlist)
for subdict in dic.values():
for key in subdict:
if key in word_counts:
subdict[key] += word_counts[key]
print(dic)
# {0: {'year': 1, 'drive': 0, 'local': 1}, 1: {'day': 2, 'element': 0, 'party': 1}, 2: {'carry': 0}}
(note that key in word_counts
is an O(1) operation)
Upvotes: 1
Reputation: 158
It is simple to store into dict after counting.
dic = {0:{'year': 0, 'drive': 0, 'local': 0,},
1:{'day': 0, 'element': 0, 'party': 0},
2:{'carry': 0}}
wordlist = ['light', 'day', 'year', 'day', 'party', 'care', 'local']
keys=[k for v in dic.values() for k in v.items() ]
dic_counts={k:wordlist.count(k) for k in keys}
dic={k1:{k2:dic_counts[k2] for k2 in v1.items()} for k1, v1 in dic.items()}
You don't need to ready keys as dict.
dic_keys = {0:['year', 'drive', 'local' ],...}
wordlist = ['light', 'day', 'year', 'day', 'party', 'care', 'local']
keys=[k for v in dic.values() for k in v.items() ]
dic_counts={k:wordlist.count(k) for k in keys}
#dic={k1:{k2:dic_counts[k2] for k2 in v1.items()} for k1, v1 in dic.items()}
dic={k1:{k2:dic_counts[k2] for k2 in v1} for k1, v1 in dic.items()}
Upvotes: 1
Reputation: 27557
Here is how you can use a nested for
loop:
dic = {0:{'year': 0, 'drive': 0, 'local': 0,},
1:{'day': 0, 'element': 0, 'party': 0},
2:{'carry': 0}}
wordlist = ['light', 'day', 'year', 'day', 'party', 'care', 'local']
for word in wordlist:
for index in dic:
if word in dic[index]:
dic[index][word] += 1
Output:
{0: {'year': 1, 'drive': 0, 'local': 1}, 1: {'day': 2, 'element': 0, 'party': 1}, 2: {'carry': 0}}
Upvotes: 2