简体   繁体   中英

Pythonic way to merge two List of tuples into single list of dict

Hi I'm pretty new to Python, so I'm not really aware of all the little tricks and shortcuts yet. I have two multi-dimensional arrays:

>>> colorStrings
[('0', '2371_9890_020'), ('1', '2371_9031_100'), ('2', '2371_9890_464')]

and

>>> skus
[('0', '0017651670'), ('0', '0017651688'), ('0', '0017651696'), ('0', '0017651704'), ('0', '0017651712'), ('0', '0017651720'), ('0', '0017651738'), ('1', '0017650896'), ('1', '0017650904'), ('1', '0017650912'), ('1', '0017650920'), ('1', '0017650938'), ('1', '0017650946'), ('1', '0017650953'), ('2', '0017651746'), ('2', '0017651753'), ('2', '0017651761'), ('2', '0017651779'), ('2', '0017651787'), ('2', '0017651795'), ('2', '0017651803')]

Basically, I want to merge these into an array of dictionary objects. Something like:

[
{
   'colorString': '2371_9890_020'
   'skus': ('0017651670', '0017651688', '0017651696', '0017651704', '0017651712', '0017651720, '0017651738')
},

{
   'colorString': '2371_9031_100'
   'skus': ('0017650896', '0017650904', '0017650912', '0017650920', '0017650938', '0017650946, '0017650953')
},

{
   'colorString': '2371_9890_464'
   'skus': ('0017651746', '0017651753', '0017651761', '0017651779', '0017651787', '0017651795, '0017651803')
}
]

Is there some kewl Pythonic way of doing this really easily using Lamba expressions or some niftiness? Thanks!

try this:

 result = [
     {
         'colorString' : color, 
         'skus' : [value for key, value in skus if key is colorkey]
     } for colorkey, color in colorStrings 
 ]

Use defaultdict to group the skus by sku_id first, then use a list comprehension to generate the combined dataset

from collections import defaultdict

sku_dict = defaultdict(list)
for color_id, sku in skus:
    sku_dict[color_id].append(sku)

combined = [dict(colorString=color, skus=sku_dict.get(color_id)) for color_id, color in colorStrings]
dict(d1, **d2)

See this related question How do I merge dicts together

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