Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add list elements into dictionary

Let's say I have dict = {'a': 1, 'b': 2'} and I also have a list = ['a', 'b, 'c', 'd', 'e']. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:

2 a
3 b
1 c
1 d
1 e
Total number of items: 8

Instead I get:

1 a
2 b
1 c
1 d
1 e
Total number of items: 6

What I have so far:

def addToInventory(inventory, addedItems)
    for items in list():
        dict.setdefault(item, [])

def displayInventory(inventory):
    print('Inventory:')
    item_count = 0
    for k, v in inventory.items():
       print(str(v) + ' ' + k)
       item_count += int(v)
    print('Total number of items: ' + str(item_count))

newInventory=addToInventory(dict, list)
displayInventory(dict)

Any help will be appreciated!

like image 471
bgrande Avatar asked Nov 30 '22 10:11

bgrande


2 Answers

You just have to iterate the list and increment the count against the key if it is already there, otherwise set it to 1.

>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     if item in d:
...         d[item] += 1
...     else:
...         d[item] = 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}

You can write the same, succinctly, with dict.get, like this

>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     d[item] = d.get(item, 0) + 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}

dict.get function will look for the key, if it is found it will return the value, otherwise it will return the value you pass in the second parameter. If the item is already a part of the dictionary, then the number against it will be returned and we add 1 to it and store it back in against the same item. If it is not found, we will get 0 (the second parameter) and we add 1 to it and store it against item.


Now, to get the total count, you can just add up all the values in the dictionary with sum function, like this

>>> sum(d.values())
8

The dict.values function will return a view of all the values in the dictionary. In our case it will numbers and we just add all of them with sum function.

like image 176
thefourtheye Avatar answered Dec 06 '22 19:12

thefourtheye


Another way:

Use collections module:

>>> import collections
>>> a = {"a": 10}
>>> b = ["a", "b", "a", "1"]
>>> c = collections.Counter(b) + collections.Counter(a)
>>> c
Counter({'a': 12, '1': 1, 'b': 1})
>>> sum(c.values())
14
like image 24
Vivek Sable Avatar answered Dec 06 '22 21:12

Vivek Sable