Reputation: 83
I have following lists.
keys = ["key1", "key2", "key3"]
value1 = [1,2]
value2 = [10,20]
value3 = [100,200]
How can I get the result like [{"key1":1, "key2":10, "key3":100},{"key1":2, "key2":20, "key3":200}]
using python?
I tried for loops but I couldn't find any solution.
Thanks in advance
Upvotes: 0
Views: 83
Reputation: 348
You can do this by using for loop. Like this
keys = ["key1", "key2", "key3"]
value1 = [1,2]
value2 = [10,20]
value3 = [100,200]
values = [value1, value2, value3]
output = [{}, {}]
for i in range(len(keys)):
output[0][keys[i]] = values[i][0]
output[1][keys[i]] = values[i][1]
print(output)
Output
[{'key1': 1, 'key2': 10, 'key3': 100}, {'key1': 2, 'key2': 20, 'key3': 200}]
Upvotes: 1
Reputation: 117856
You can use a list comprehension to first zip
your values elementwise, then create dictionaries by zipping those against your keys.
>>> [dict(zip(keys, i)) for i in zip(value1, value2, value3)]
[{'key1': 1, 'key2': 10, 'key3': 100}, {'key1': 2, 'key2': 20, 'key3': 200}]
Upvotes: 5