0

I'm attempting to convert multiple lists into a dictionary where the initial list contains the keys.

For example:

list_keys = ['a' , 'b']
list_vals_1 = ['tick' , 'tack']
list_vals_2 = ['big' , 'small']

is transformed into:

expected = {}
expected['a'] = ('tick' , 'big')
expected['b'] = ('tack', 'small')
print('expected' , expected)

I could transform the lists using into a dictionary using:

mappings = {}
i = 0
for l in list_keys :
    mappings[l] = (list_vals_1[i] , list_vals_2[i])
    i = i + 1

Is there a cleaner/better solution using Python to accomplish this ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • Related: [How do I convert two lists into a dictionary?](https://stackoverflow.com/q/209840/4518341) – wjandrea Feb 13 '21 at 18:35

2 Answers2

2

try zip

dict(zip(list_keys, zip(list_vals_1, list_vals_2)))
{'a': ('tick', 'big'), 'b': ('tack', 'small')}
Epsi95
  • 8,832
  • 1
  • 16
  • 34
1

Use zip():

>>> {k: (v1, v2) for k, v1, v2 in zip(list_keys, list_vals_1, list_vals_2)}
{'a': ('tick', 'big'), 'b': ('tack', 'small')}

Also, for what it's worth, you could have used enumerate() to improve your existing solution:

for i, k in enumerate(list_keys):
    mappings[k] = (list_vals_1[i], list_vals_2[i])

By the way, note that l is a bad variable name since it looks like 1 and I. I used k instead - short for "key".

wjandrea
  • 28,235
  • 9
  • 60
  • 81