Home > Back-end >  how to construct a dictionary from two lists mapping that key to the value at the corresponding inde
how to construct a dictionary from two lists mapping that key to the value at the corresponding inde

Time:10-17

if I have two lists:

keys = [("a", 2), ("b", 0), ("c", 2)]

values = [0, 10, 20]

how could I write a loop that maps the fist element in the tuple from keys to a value in values according to the position in specified in the tuple.

for example this case it should return:

{'a': 20, 'b': 0, 'c': 20}

CodePudding user response:

You can iterate over tuple then use second element on each tuple as index and search on values and create dict like below:

>>> keys = [("a", 2), ("b", 0), ("c", 2)]

>>> values = [0, 10, 20]

>>> {k: values[idx] for k,idx in keys}
{'a': 20, 'b': 0, 'c': 20}

CodePudding user response:

You can create a dict from a list of key, value tuples like so:

>>> dict((k,values[i]) for (k,i) in keys)
{'a': 20, 'b': 0, 'c': 20} 
  • Related