views:

406

answers:

3

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?

+12  A: 
>>> 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.

balpha
If a,b,c will be huge, I recommend izip from itertools module.
lionbest
@lionbest: Good point, I've added that.
balpha
+1  A: 

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])
rincewind
A: 

if the order of these things matters, you should not use a dictionary. by definition, they are unordered. you can use one of the many ordered_dictionary implementations floating around, or wait for python 2.7 or 3.1 which will include an ordered dictionary implementation in the collections module.

Autoplectic