简体   繁体   中英

Group list of dictionary based on particular key and add another value to it?

I have list of dictionaries like these

l = [
     {'vehicle': 708.75, 'general': None, 'salesperson': 'SAJANEESH'},
     {'vehicle': None, 'general': 1044.48, 'salesperson': 'SAJANEESH'},
     {'vehicle': None, 'general': 7035.0, 'salesperson': 'MATHEW'},
    ]

I am trying to change the form new list of dictionary like this .

expected output

l = [
     {'vehicle': 708.75, 'general': 1044.48, 'salesperson': 'SAJANEESH'},
     {'vehicle': None, 'general': 7035.0, 'salesperson': 'MATHEW'},
    ]

I am trying to group the salesperson and add general or vehicle value to it. I try like this

import collections
res = collections.defaultdict(list) 
for i in l:
    for key, val in i.items(): 
        res[val].append(key) 
print(res)

but it shows wrong result.any suggestions to get this??

You can use simply iterating through the datastructure

[root@cscale-82-69 python]# cat stck.py
l = [
     {'vehicle': 708.75, 'general': None, 'salesperson': 'SAJANEESH'},
     {'vehicle': None, 'general': 1044.48, 'salesperson': 'SAJANEESH'},
     {'vehicle': None, 'general': 7035.0, 'salesperson': 'MATHEW'},
    ]


y = []
for each in l:
 name = each['salesperson']
 count = 0
 for _ in y:
  if _['salesperson'] == name:
   count += 1
   for key, val in _.items():
    if _[key] == None:
     _[key] = each[key]
 if count == 0:
  y.append(each)

print (l)
print (y)
[root@cscale-82-69 python]# python stck.py
[{'general': 1044.48, 'salesperson': 'SAJANEESH', 'vehicle': 708.75}, {'general': 1044.48, 'salesperson': 'SAJANEESH', 'vehicle': None}, {'general': 7035.0, 'salesperson': 'MATHEW', 'vehicle': None}]
[{'general': 1044.48, 'salesperson': 'SAJANEESH', 'vehicle': 708.75}, {'general': 7035.0, 'salesperson': 'MATHEW', 'vehicle': None}]
[root@cscale-82-69 python]#

You can use itertools.groupby for unique lists:

from itertools import groupby
from operator import itemgetter

key = itemgetter('vehicle')
print([next(v) for _, v in groupby(sorted(l, key=key), key=key)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM