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?
>>> 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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With