简体   繁体   中英

how to construct a dictionary from two lists mapping that key to the value at the corresponding index in the list of values in python

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}

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}

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} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM