Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Dictionaries

I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?

like image 814
pythonicate Avatar asked Aug 05 '09 12:08

pythonicate


2 Answers

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>> dict(zip(a, zip(b, c)))
{1: (4, 7), 2: (5, 8), 3: (6, 9)}

See the documentation for more info on zip.

As lionbest points out below, you might want to look at itertools.izip() if your input data is large. izip does essentially the same thing as zip, but it creates iterators instead of lists. This way, you don't create large temporary lists before creating the dictionary.

like image 138
balpha Avatar answered Oct 25 '22 09:10

balpha


Python 3:

combined = {name:dict(data1=List_2[i], data2=List_3[i]) for i, name in enumerate(List_1)}

Python 2.5:

combined = {}
for i, name in enumerate(List_1):
    combined[name] = dict(data1=List_2[i], data2=List_3[i])
like image 41
rincewind Avatar answered Oct 25 '22 08:10

rincewind