Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
5 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))

Learn more about Python from an expert. Enroll in our Python Course.

0 votes
by (106k 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:-

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...