8.4. Dictionary Comprehension - Filtering#

dict1={
    'A':1,
    'B':2,
    'C':3,
    'D':4,
    'E':5
}
dict1
{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

8.4.1. Filter based on Values#

{x:y for x,y in dict1.items() if y>3}   # Note: here x:y is returned instead of x,y because of format of dict we need
{'D': 4, 'E': 5}

8.4.2. If else Conditions:#

  • Syntax:{ (x if else):(y if else) for x,y in dict1.items()}

8.4.2.1. on Keys#

# Start by writting normal condition { x:y for x,y in dict1.items()}
{ (x.lower() if x=='C' else x) :y for x,y in dict1.items()}
{'A': 1, 'B': 2, 'c': 3, 'D': 4, 'E': 5}

8.4.2.2. on Values#

# Start by writting normal condition { x:y for x,y in dict1.items()}
{ x: (y*40 if y==4 else y) for x,y in dict1.items()}
{'A': 1, 'B': 2, 'C': 3, 'D': 160, 'E': 5}