Python - Dictionary Dictionary comprehensions

Introduction

You can create dictionary with a dictionary comprehension expression.

The following code builds a dictionary with a key/value pair for every such pair in the zip result:

Demo

D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])} 
print( D )

Result

We can use them to map a single stream of values to dictionaries as well, and keys can be computed with expressions just like values:

Demo

D = {x: x ** 2 for x in [1, 2, 3, 4]}        # Or: range(1, 5) 
print( D )

D = {c: c * 4 for c in 'TEST'}               # Loop over any iterable 
print( D )

D = {c.lower(): c + '!' for c in ['TEST', 'EGGS', 'HAM']} 
print( D )# from w  w w.ja va2  s . c o  m

Result

Dictionary comprehensions are useful for initializing dictionaries from keys lists.

Demo

D = dict.fromkeys(['a', 'b', 'c'], 0)        # Initialize dict from keys 
print( D )

D = {k:0 for k in ['a', 'b', 'c']}           # Same, but with a comprehension 
print( D )
D = dict.fromkeys('test')                    # Other iterables, default value 
print( D ) 

D = {k: None for k in 'test'} 
print( D )# from   w  w w .  j  ava  2 s  .co m

Result