We have a dictionary: items = {'coin': 43, 'apple': 5} How to add new values ​​from the list here: new = ['coin', 'coin', 'apple', 'axe', 'sword'] ?

  • Do you know how to add new values ​​to the dictionary? And how to get values ​​from the list? What are the difficulties? - Nick Volynkin
  • If the values ​​from the list become keys in the dictionary, then what will become the values? How to handle duplicate list items (like a coin )? - Nick Volynkin
  • I know, I need to write the function dict (x, y) to add values ​​from the list to the dictionary, where x is the dictionary, and y is the list - David
  • Actually this is the case, how to add the values ​​of duplicate elements and add new elements with new values - David
  • Related question: Add two dictionaries - jfs

3 answers 3

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.