Dictionary comprehension

Documentation

  1. In the Python Tutorial
    1. list comprehension
    2. set comprehension
    3. dict comprehension
  2. In the Python Language Reference
    1. comprehensions

list comprehension

A list comprehension is an alternative to repeated calls to append.

oldPrices = [   #a list of floats
    10.00,
    20.00,
    30.00
]

#Inflate the price of each item by 6 percent.

newPrices = [1.06 * price for price in oldPrices]

for price in newPrices:
    print(f"${price:5.2f}")
$10.60
$21.20
$31.80

set comprehension

A set comprehension is an alterative to repeated calls to add.

oldFurniture = {   #a set of strings
    "chair",
    "table",
    "bed"
}

newFurniture = {item.capitalize() for item in oldFurniture}

for item in newFurniture:
    print(item)
Table
Chair
Bed

dict comprehension

A dict comprehension is an alternative to repeated calls to update.

oldPrices = {   #a dictionary
    "chair": 10.00,
    "table": 20.00,
    "bed":   30.00
}

#Inflate the price of each item by 6 percent.

newPrices = {key.capitalize(): 1.06 * value for key, value in oldPrices.items()}

for key, value in newPrices.items():
    print(f"{key:5} ${value:5.2f}")
Chair $10.60
Table $21.20
Bed   $31.80