+1 vote
4 views
in Python by (130 points)
edited by

Can the Python list comprehension syntax be used to create dictionaries? 

For an example: By iterating over pairs of keys and values

mydict = {(a,b) for (a,b) in blaa blaa blaa} #doesn't work

2 Answers

+4 votes
by (10.9k points)
edited by

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))

0 votes
by (95.7k points)

You can create a dictionary comprehension by using the below code:

d = {k:v for k, v in iterable}

You can use the following video tutorials to clear all your doubts:-

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...