Python | Dictionary Comprehension
Start your free 7-days trial now!
Dictionary comprehension in Python allows us to create a new dictionary in a short, efficient manner.
Syntax
Basic
{key expression: value expression for variable in iterable}
Conditional
{output expression + conditional on output for variable in iterable + conditional on iterable}
Examples
Basic
To create a dictionary with keys 1 ~ 3, and values as 2*key
:
For every element i
in the range(1,4)
, we are adding a key-value pair i: 2*i
to the doubles
dictionary.
To create a new dictionary d_new
by doubling the values of an existing dictionary d_old
:
Conditional
Input condition
To specify a condition on the input:
Here, we only loop through (key,value)
in the for
loop where key
does not equal 'c'
. Hence, we do not see any key-value pair in the output with key 'c'
.
To specify multiple conditions on the input:
d_old = {'a': 1, 'b': 2, 'c': 3}
{'b': 4}
Here we specify two conditions for the input iterable d_old
:
1) key
must not equal 'c'
2) value
must be divisible by 2
Output condition
To specify a condition on the output:
Here, we add key:value*2
to d_new
if the key does not equal 'c'
, otherwise we add key:value*3
. Notice how only the value of key 'c'
has been multiplied by 3 while the value of keys 'a'
and 'b'
have only been multiplied by 2.