We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Dictionary Comprehensions

If list comprehensions build lists, dictionary comprehensions build dictionaries. Say you have a list of game records:

games = [
    {"game_id": "g-01", "title": "The Legend of Zelda", "status": "released"},
    {"game_id": "g-02", "title": "Silksong", "status": "delayed"},
    {"game_id": "g-03", "title": "Hades II", "status": "released"},
]

and want a dictionary where you can lookup game_id --> title. You can use a dictionary comprehension:

game_titles = {game["game_id"]: game["title"] for game in games}
print(game_titles)
# {'g-01': 'The Legend of Zelda', 'g-02': 'Silksong', 'g-03': 'Hades II'}

To filter records while creating the dictionary, you can optionally add an if condition:

released_titles = {
    game["game_id"]: game["title"] for game in games if game["status"] == "released"
}
print(released_titles)
# {'g-01': 'The Legend of Zelda', 'g-03': 'Hades II'}

So, to be precise, the syntax is:

{key_expression: value_expression for item in iterable if condition}

Assignment

Complete the map_active_models function. It accepts a list of device dictionaries and returns a new dictionary that maps each active device's device_id to its model name.