2

I have 3 lists and one string like this:

a = ['a', 'b', 'c']
b = [1, 2, 3, 4, 5]
c = [10, 11, 14, 15, 16]

string = 'buy'

I need a list of dictionaries like this:

[{'a':1 , 'b':10 , 'c':'buy'},{'a':2 , 'b':11 , 'c':'buy'},{'a':3 , 'b':14 , 'c':'buy'},...]
Tonechas
  • 13,398
  • 16
  • 46
  • 80
Farbod
  • 21
  • 2

4 Answers4

3
result = [ dict(zip(a,[*v, 'buy'])) for v in zip(b,c) ]
Błotosmętek
  • 12,717
  • 19
  • 29
2

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'))]
Mark
  • 90,562
  • 7
  • 108
  • 148
2

This should do what you're looking for:

[{a[0]:vb, a[1]:vc, a[2]:string} for vb, vc in zip(b, c)]

It produces:

[{'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'}]

It takes the dict keys from list a, and 'buy' comes from string.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
1

You can use zip(), list comprehension and dictionary comprehension for your task

Try this:

a = ['a', 'b', 'c']
b = [1, 2, 3, 4, 5]
c = [10, 11, 14, 15, 16]

print([{ a[0]:i, a[1]:j, a[2]:'buy'} for i,j in zip(b,c)])

OR

print([dict(zip(a, [i, j, "buy"])) for i,j in zip(b,c)])

Outputs:

[{'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'}]
abhiarora
  • 9,743
  • 5
  • 32
  • 57