Reputation: 43
(1) : This does work, but it doesn't accumulate.
word_dict = {'now': 3, 'this': 3, 'now': 2, 'this': 2}
new_word_dict = {}
for word in word_dict:
n = word_dict.get(word)
new_word_dict[word] = n
print(new_word_dict)
(1) the result
{'now': 2}
{'now': 2, 'this': 2}
(2) : This doesn't work. What the KeyError is ?
word_dict = {'now': 3, 'this': 3, 'now': 2, 'this': 2}
new_word_dict = {}
for word in word_dict:
n = word_dict.get(word)
new_word_dict[word] += n
print(new_word_dict)
(2) the result
----> new_word_dict[word] += n
KeyError: 'now'
Upvotes: 0
Views: 361
Reputation: 395
The KeyError is because the key you're trying to increment doesn't exist, but I think there's more than just this issue in your example.
Assuming that the result you want is new_word_dict
to be an accumulation of word_dict
you first need to change the type of word_dict
to a list of tuples (because, as @deceze pointed out in a comment, duplicate keys aren't allowed in dicts). So I think you want to end up with something like this:
words == [("now", 3), ("this", 3), ("now", 2), ("this", 2)]
words_accumulated == {"now": 5, "this": 5}
then your loop could be changed to
words = [("now", 3), ("this", 3), ("now", 2), ("this", 2)]
words_accumulated = {}
for word, val in words: # unpack each tuple into two variables
existing_val = words_accumulated.setdefault(word, 0) # if it doesn't exist yet, set to 0. This solves your KeyError
words_accumulated[word] = existing_val + val
For further research on how to do this better, look up defaultdict and maybe some of the tools in itertools
Upvotes: 1
Reputation: 146
new_word_dict[word] += n
need the latest value of new_word_dict[word] if it's not initialize it should crash.
to fix this, you can check if new_word_dict exist like
new_word_dict[word] = n if new_word_dict[word] else new_word_dict[word] + n
You can use too word_dict.items() like for key, value in word_dict.items()
Upvotes: 0