Python counter not recognizing dictionary
Question: I have a list and a dictionary and I want to ultimately find a sum of the
values in the two. For example, I want the code below to return :

    
    
    {gold coin : 45, rope : 1, dagger : 6, ruby : 1}
    

First I right a function to turn the dragonLoot list into a dictionary and
then I run a Counter to add the two dictionaries together. However, when I run
the code I get the following:

    
    
    {'ruby': 1, 'gold coin': 3, 'dagger': 1}
    Counter({'gold coin': 42, 'dagger': 5, 'rope': 1})
    

For some reason it looks like the Counter is not recognizing the dictionary
that I create from dragonLoot. Does anyone have any suggestions on what I am
doing wrong? Thanks!

    
    
    inv = {'gold coin' : 42, 'rope' : 1, 'dagger' : 5}
    dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
    
    def inventory(item):
        count = {}
        for x in range(len(item)):
            count.setdefault(item[x],0)
            count[item[x]] = count[item[x]] + 1
        print(count)
    
    inv2 = inventory(dragonLoot)
    
    from collections import Counter
    dicts = [inv,inv2]
    c = Counter()
    for d in dicts:
        c.update(d)
    
    print(c)
    


Answer: You are not returning the count in your inventory method:

    
    
    def inventory(item):
        count = {}
        for x in range(len(item)):
            count.setdefault(item[x],0)
            count[item[x]] = count[item[x]] + 1
        print(count)
    

You are simply printing your inventory calculation. Change that print to a
return, or add a return line after the print:

    
    
    def inventory(item):
        count = {}
        for x in range(len(item)):
            count.setdefault(item[x],0)
            count[item[x]] = count[item[x]] + 1
        print(count)
        return count
    

Adding that to your code and running it, gives this output:

    
    
    Counter({'gold coin': 45, 'dagger': 6, 'rope': 1, 'ruby': 1})
    

Alternatively, the implementation provided by @nneonneo is optimal.

