You can just zip b
and c
and use it to make the dictionaries in a comprehension:
a = ['a', 'b', 'c']
b = [1, 2, 3, 4, 5]
c = [10, 11, 14, 15, 16]
[{'a':a, 'b':b, 'c':'buy'} for a, b, in zip(b,c)]
Result:
[{'a': 1, 'b': 10, 'c': 'buy'},
{'a': 2, 'b': 11, 'c': 'buy'},
{'a': 3, 'b': 14, 'c': 'buy'},
{'a': 4, 'b': 15, 'c': 'buy'},
{'a': 5, 'b': 16, 'c': 'buy'}]
If you want to include the keys from a
dynamically, you can zip them in too with something like itertools zip_longest
to grab the static string:
from itertools import zip_longest
a = ['a', 'b', 'c']
b = [1, 2, 3, 4, 5]
c = [10, 11, 14, 15, 16]
[dict(zip_longest(a, tup, fillvalue='buy')) for tup in zip(b,c)]
Same result:
[{'a': 1, 'b': 10, 'c': 'buy'},
{'a': 2, 'b': 11, 'c': 'buy'},
{'a': 3, 'b': 14, 'c': 'buy'},
{'a': 4, 'b': 15, 'c': 'buy'},
{'a': 5, 'b': 16, 'c': 'buy'}]
Yet another way is to use itertools.repeat()
to include the static string in the zipped tuple:
from itertools import repeat
a = ['a', 'b', 'c']
b = [1, 2, 3, 4, 5]
c = [10, 11, 14, 15, 16]
[dict(zip(a, tup)) for tup in zip(b,c, repeat('buy'))]