Mike Christensen
Mike Christensen

Reputation: 91666

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!

Upvotes: 8

Views: 3343

Answers (2)

Imran
Imran

Reputation: 91069

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]

Upvotes: 9

Cédric Julien
Cédric Julien

Reputation: 80811

try this :

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

Upvotes: 10

Related Questions