Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 336
Mike Christensen Avatar asked Apr 29 '11 06:04

Mike Christensen


2 Answers

try this :

 result = [
     {
         'colorString' : color, 
         'skus' : [value for key, value in skus if key is colorkey]
     } for colorkey, color in colorStrings 
 ]
like image 195
Cédric Julien Avatar answered Sep 22 '22 01:09

Cédric Julien


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]
like image 23
Imran Avatar answered Sep 26 '22 01:09

Imran