Reputation: 1889
I have 2 lists and I want to merge them as list of dictionaries. The code I have:
import pprint
list1 = [1, 2, 3, 4]
list2 = [0, 1, 1, 2]
newlist = []
for i in range(0, len(list1)):
newdict = {}
newdict["original"] = list1[i]
newdict["updated"] = list2[i]
newlist.append(newdict)
pprint.pprint(newlist)
Output:
[{'original': 1, 'updated': 0},
{'original': 2, 'updated': 1},
{'original': 3, 'updated': 1},
{'original': 4, 'updated': 2}]
Is there a better or faster way to do this?
Upvotes: 2
Views: 319
Reputation: 1341
The answer provided by idjaw nails it in a very Pythonic way. There is an alternative approach using named tuples:
from collections import namedtuple
from itertools import izip
ListCompare = namedtuple('ListCompare', ['original', 'updated'])
L1 = [1,2,3,4]
L2 = [0,1,1,2]
comp = [ListCompare(a, b) for a,b in izip(L1, L2)]
print comp[1].original, comp[1].updated
2 1
Named tuples should perform better (i.e. less overhead) than dictionaries if the lists are long. Just though I'd mention this less known alternative. Note that this code is for Python 2.7, for Python 3 one must make minor adjustments.
Upvotes: 0
Reputation: 26578
You can zip your two lists and then use a list comprehension, where you create your dictionary as each item in the list:
list1=[1,2,3,4]
list2=[0,1,1,2]
new_list = [{'original': v1, 'updated': v2} for v1, v2 in zip(list1, list2)]
print(new_list)
Output:
[{'updated': 0, 'original': 1}, {'updated': 1, 'original': 2}, {'updated': 1, 'original': 3}, {'updated': 2, 'original': 4}]
Upvotes: 13
Reputation: 1
You could also iterate over both lists at every index with a list comprehension. As is, this will throw an index error if list1 is larger than list2. Anyone know if zip is faster?
newlist = [{"original":list1[i],"updated":list2[i]} for i in range(len(list1))]
Upvotes: 0