How to add list elements into dictionary

Question:

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!

Asked By: bgrande

||

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.

Answered By: 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
Answered By: Vivek Sable

Use collections.Counter, as it has everything you need for the task at hand:

from collections import Counter

the_list = ['a', 'b', 'c', 'd', 'e']

counter = Counter({'a': 1, 'b': 2})
counter.update(the_list)

for c in sorted(counter):
    print c, counter[c]

In order to get the total count you can simply sum the values of the counter:

sum(counter.values())
# 8
Answered By: Matt
stuff={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

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

def addToInventory(inventory,addedItems):
    for v in addedItems:
        if v in inventory.keys():
            inventory[v]+=1
        else:
            inventory[v]=1

addToInventory(stuff,dragonLoot)    

displayInventory(stuff)
Answered By: Jonathan Pradas
def addToInventory(inventory, addedItems):
    for v in addedItems:
        if v in inventory.keys():
            inventory[v] += 1
        else:
            inventory[v] = 1
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
Answered By: Rusher

If you are looking for a solution for the List to Dictionary Function for Fantasy Game Inventory in Automating boring stuff with Python, here is a code that works:

# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

#this part of the code displays your current inventory
def displayInventory(inventory): 
    print('Inventory:')
    item_total = 0

    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

#this launches the function that displays your inventory
displayInventory(stuff) 

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# this part is the function that adds the loot to the inventory
def addToInventory (inventory, addedItems): 

    print('Your inventory now has:')

#Does the dict has the item? If yes, add plus one, the default being 0
    for item in addedItems:
        stuff[item] = stuff.get(item, 0) + 1 


# calls the function to add the loot
addToInventory(stuff, dragonLoot) 
# calls the function that shows your new inventory
displayInventory(stuff) 
Answered By: Adrien Le Falher

For the first section of this question this is the code that I came up with.

invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print ("Inventory:")
total = sum(invt.values())
for x, v in invt.items():
  print (str(v) + ' ' + x)
print ("Total number of items: {}".format(total))

I see that most people are interating through the loop to add to the total variable. However using the sum method, I skipped a step ..

Always open to feedback….

Answered By: Taurean Branch

The question on ‘List to Dictionary Function for Fantasy Game Inventory’ – Chapter 5. Automate the Boring Stuff with Python.

# This is an illustration of the dictionaries

# This statement is just an example inventory in the form of a dictionary
inv = {'gold coin': 42, 'rope': 1}
# This statement is an example of a loot in the form of a list
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# This function will add each item of the list into the dictionary
def add_to_inventory(inventory, dragon_loot):

    for loot in dragon_loot:
        inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0
        inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1

    return inventory

# This function will display the dictionary in the prescribed format
def display_inventory(inventory):

    print('Inventory:')
    total_items = 0

    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        total_items = total_items + 1

    print('Total number of items: ' + str(total_items))

# This function call is to add the items in the loot to the inventory
inv = add_to_inventory(inv, dragon_loot)

# This function call will display the modified dictionary in the prescribed format
display_inventory(inv)
Answered By: Ashutosh Kar
invent = {'rope': 1, 'torch':6, 'gold coin': 42, 'dagger':1, 'arrow':12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

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

def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory.setdefault(item, 0)
        inventory[item] = inventory[item] + 1
    return(inventory)



displayInventory(addToInventory(invent, dragonLoot))

Below is the code with the use of the above tips plus a slight variation with the plural of nouns. For those who are willing and brave, there is the task of ifs and elifs for exceptions 😉

# sets your dictionary
backpack = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

# this function display your current inventory
def displayInventory(inventory):
    print("Backpack:")
    itemTotal = 0
    for k, v in inventory.items():

    # creates a simple plural version of the noun 
    # (adds only the letter "s" at the end of the word) does not include exceptions 
    # (for example, torch - 'torchs' (should be 'torches'), etc.
        if v > 1:
            print(str(v) + ' ' + k +'s')
        else:
            print(str(v) + ' ' + k)

        itemTotal += v
    print("Total quantity of items: " + str(itemTotal))

# sets your loot 
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# this function adds your loot to your inventory
def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory[item] = inventory.get(item,0) + 1

# launch your functions
addToInventory(backpack, dragonLoot)
displayInventory(backpack)
Answered By: NobleCat

For the first part of your question, to add the list items to the dictionary, I used this code:

inventory = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

def addToInventory(inventory, addedItems):
    for i in addedItems:
        if i in inventory:
            inventory[i] = inventory[i] + 1
        else:
            inventory[i] = 1 #if the item i is not in inventory, this adds it
                             #   and gives the value 1.



I share it because I used the if statement inseat of the .get function, as the other comments. Now that I leard the .get it seems simpler and shorter than my code. But at the chapter in the book “Automate Boring stuff” where I encountered this exercise, I hadn’t learned (or well enough) the .get function.

As for the function that displays the inventory, I have the same code as other comments :

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

I call the two functions, and the result is as follows:

>>> addToInventory(inventory, dragonLoot)
>>> displayInventory(inventory)

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby

Total of number of items: 48

I hope this helps.

Answered By: Saywa

inventory.py :

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

#this part of the code displays your current inventory
def displayInventory(inventory): 
    print('Inventory:')
    item_total = 0

    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

#this launches the function that displays your inventory
displayInventory(stuff) 

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# this part is the function that adds the loot to the inventory
def addToInventory (inventory, addedItems): 

    print('Your inventory now has:')

#Does the dict has the item? If yes, add plus one, the default being 0
    for item in addedItems:
        stuff[item] = stuff.get(item, 0) + 1 


# calls the function to add the loot
addToInventory(stuff, dragonLoot) 
# calls the function that shows your new inventory
displayInventory(stuff) 
Answered By: Alex.ylink
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.