Issue
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!
Solution
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.
Answered By - thefourtheye
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.