I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work
Using dict() method we can convert list comprehension to the dictionary.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
How to create a dictionary with list comprehension in Python? The zip () function which is an in-built function, provides a list of tuples containing elements at same indices from two lists. If two lists are keys and values respectively, this zip object can be used to constructed dictionary object using another built-in function dict ()
We can create dictionaries using simple expressions. Let’s see a example,lets assume we have two lists named keys and value now, We can use Dictionary comprehensions with if and else statements and with other expressions too. This example below maps the numbers to their cubes that are not divisible by 4:
Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax. A dictionary comprehension takes the form {key: value for (key, value) in iterable}.
If two lists are keys and values respectively, this zip object can be used to constructed dictionary object using another built-in function dict () In Python 3.x a dictionary comprehension syntax is also available to construct dictionary from zip object
Use a dict comprehension (Python 2.7 and later):
{key: value for (key, value) in iterable}
Alternatively for simpler cases or earlier version of Python, use the dict
constructor, e.g.:
pairs = [('a', 1), ('b', 2)] dict(pairs) #=> {'a': 1, 'b': 2} dict([(k, v+1) for k, v in pairs]) #=> {'a': 2, 'b': 3}
Given separate arrays of keys and values, use the dict
constructor with zip
:
keys = ['a', 'b'] values = [1, 2] dict(zip(keys, values)) #=> {'a': 1, 'b': 2}
2) "zip'ped" from two separate iterables of keys/vals dict(zip(list_of_keys, list_of_values))
In Python 3 and Python 2.7+, dictionary comprehensions look like the below:
d = {k:v for k, v in iterable}
For Python 2.6 or earlier, see fortran's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With