Home > Back-end >  Is there a function for mapping each elem of an iter. seq. to corresponding ones of another?
Is there a function for mapping each elem of an iter. seq. to corresponding ones of another?

Time:02-28

I know that dict.fromkeys(a, b) takes an iterable sequence of keys (a), but only takes one (optional) value (None by default). I also know that update({k1: v1, k2: v2...}) takes either a dictionary, or something like a list of (key, value) tuples. But I have been unable to find a method that looks something like:-

new_dict = dict.method(lst1, lst2) that maps each element of lst1 to corresponding element of lst2.

I am aware that I could use the map() function, with, say, a lambda as an argument or something similar, but I was looking for a direct (more efficient?) replacement.

Thanks!

CodePudding user response:

Use zip to zip the lists together into (key, value) tuples, and then pass the result to dict().

>>> lst1 = ['foo', 'bar']
>>> lst2 = [42, True]
>>> dict(zip(lst1, lst2))
{'foo': 42, 'bar': True}
  • Related