Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of dictionaries - adding the dicts with same key names [duplicate]

I have a python list like this:

user = [
        {'name': 'ozzy', 'quantity': 5},
        {'name': 'frank', 'quantity': 4},
        {'name': 'ozzy', 'quantity': 3},
        {'name': 'frank', 'quantity': 2},
        {'name': 'james', 'quantity': 7},
        ]

I am trying to write the code to join the dictionaries with the same name by also adding the quantities. The final list will be that:

user = [
        {'name': 'ozzy', 'quantity': 8},
        {'name': 'frank', 'quantity': 6},
        {'name': 'james', 'quantity': 7}
        ]

I have tried a few things but I am struggling to get the right code. The code I have written below is somewhat adding the values (actually my list is much longer, I have just added a small portion for reference).

newList = []
    quan = 0
    for i in range(0,len(user)):      
        originator = user[i]['name']
        for j in range(i+1,len(user)):
            if originator == user[j]['name']:
                quan = user[i]['quantity'] + user[j]['quantity']
                newList.append({'name': originator, 'Quantity': quan})

can you please help me to get the correct code?

like image 670
Rikkas Avatar asked Apr 18 '18 09:04

Rikkas


People also ask

Can Dicts have duplicates?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can Dicts have same keys?

In this article, we will find out whether a dictionary has duplicate keys or not in Python. The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

What will happen if a dictionary has duplicate keys Python?

Dictionary literals are constructed in the order given in the source. This means that if a key is duplicated the second key-value pair will overwrite the first as a dictionary can only have one value per key.

What happens when a dictionary has 2 items with the same key value?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


2 Answers

Just count the items in a collections.Counter, and expand back to list of dicts if needed:

user = [
        {'name': 'ozzy', 'quantity': 5},
        {'name': 'frank', 'quantity': 4},
        {'name': 'ozzy', 'quantity': 3},
        {'name': 'frank', 'quantity': 2},
        {'name': 'james', 'quantity': 7},
        ]

import collections

d = collections.Counter()
for u in user:
    d[u['name']] += u['quantity']

print(dict(d))

newlist = [{'name' : k, 'quantity' : v} for k,v in d.items()]

print(newlist)

outputs Counter dict first, which is already sufficient:

{'frank': 6, 'ozzy': 8, 'james': 7}

and the reformatted output using list of dicts:

[{'name': 'frank', 'quantity': 6}, {'name': 'ozzy', 'quantity': 8}, {'name': 'james', 'quantity': 7}]
like image 177
Jean-François Fabre Avatar answered Oct 13 '22 00:10

Jean-François Fabre


The solution is also straightforward with a standard dictionary. No need for Counter or OrderedDict here:

user = [
        {'name': 'ozzy', 'quantity': 5},
        {'name': 'frank', 'quantity': 4},
        {'name': 'ozzy', 'quantity': 3},
        {'name': 'frank', 'quantity': 2},
        {'name': 'james', 'quantity': 7},
        ]

dic = {}
for item in user:
  n, q = item.values()
  dic[n] = dic.get(n,0) + q
print(dic)

user = [{'name':n, 'quantity':q} for n,q in dic.items()]
print(user)

Result:

{'ozzy': 8, 'frank': 6, 'james': 7}
[{'name': 'ozzy', 'quantity': 8}, {'name': 'frank', 'quantity': 6}, {'name': 'james', 'quantity': 7}]
like image 20
sciroccorics Avatar answered Oct 12 '22 22:10

sciroccorics