We have a dictionary: items = {'coin': 43, 'apple': 5} How to add new values from the list here: new = ['coin', 'coin', 'apple', 'axe', 'sword'] ?
|
3 answers
Counter returns a dictionary with counted list items.
items = {'coin': 43, 'apple': 5} new = ['coin', 'coin', 'apple', 'axe', 'sword'] from collections import Counter def add_to_dict(x: dict, y: list): for k, v in Counter(y).items(): x[k] = x.get(k, 0) + v add_to_dict(items, new) print(items) |
Code:
new = ['coin', 'coin', 'apple', 'axe', 'sword'] items = {'coin': 43, 'apple': 5} for x in new: if x in items: items[x] += 1 else: items[x] = 0 print(items) Result:
#{'sword': 0, 'coin': 45, 'apple': 6, 'axe': 0} |
To add new items by updating the number of old ones, if necessary:
>>> from collections import Counter >>> Counter(items) + Counter(new) Counter({'coin': 45, 'apple': 6, 'axe': 1, 'sword': 1}) It can be seen that it is convenient to use Counter as a set (set) of elements that can be repeated - a multiset (multiset) . Counter can also be used as a normal dictionary, so the result can be left as is without converting to dict — given the task, on the contrary, you should initially use Counter instead of dict.
|
coin)? - Nick Volynkin ♦