IniziaInizia gratis

Adding and extending dictionaries

If you have a dictionary and you want to add data to it, you can simply create a new key and assign the data you desire to it. It's important to remember that if it's a nested dictionary, then all the keys in the data path must exist, and each key in the path must be assigned individually.

You can also use the .update() method to update a dictionary with a list of keys and values from another dictionary, tuples or keyword arguments.

The squirrels_by_park dictionary is already loaded for you, which is keyed by the park name and the value is a tuple with the main color, highlights, action, and reaction to humans.

Questo esercizio fa parte del corso

Data Types in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Assign the squirrels_madison list as the value to the 'Madison Square Park' key of the squirrels_by_park dictionary.
  • Update the 'Union Square Park' key in the squirrels_by_park dictionary with the data in the squirrels_union tuple.
  • Loop over the squirrels_by_park dictionary.
    • Print the park_name and a list of all primary_fur_colors for squirrels safely in that park using a list comprehension; return 'N/A' if the key isn't found.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# Assign squirrels_madison as the value to the 'Madison Square Park' key
____[____] = ____

# Update squirrels_by_park with the squirrels_union tuple
____.____([____])

# Loop over the park_name in the squirrels_by_park dictionary 
for park_name in ____:
    # Safely print a list of the primary_fur_color for each squirrel in park_name
    print(park_name, [____.get('____', '____') for squirrel in ____[____]])  
Modifica ed esegui il codice