For Python 2.6 and older versions, you can pass a list comprehension or generator expression to the dictionary using:
dict((key, func(key)) for key in keys)
Now, for Python 2.7 and higher versions, you can use the dictionary comprehension syntax directly:
{key: value for (key, value) in iterable}
Ex-
keys=[x,y,z]
values=[5,4,3]
mydict = { a:b for (a,b) in zip(keys, values)}
print(mydict)
Output-{‘x’:5, ‘y’:4, ‘z’:3}
Similarly, you can simply call the dictionary instead of list comprehension if you already have iterables of keys or values.
1.For a pair of values or keys use:
dict(keypairs)
2.For two separate values or keys use:
dict(zip(listofkeys, listofvalues))
Learn more about Python from an expert. Enroll in our Python Course.