Recall that a Python dictionary is a collection of key-value pairs where each key is unique and is used to store and retrieve its associated value. Dictionaries are mutable, meaning they can be changed after they are created. They are also ordered meaning that items retain the order in which they were added.
Using the example of calendars, a dictionary could be used to map the names of months to the number of days they contain:
In this example, calendar_days is a dictionary where each key is a string representing a month, and each value is an integer representing the number of days in that month. You can access the number of days in a specific month by using the month name as a key as done above for February, which will return the result of 28.
Note that in the above dictionary, we forgot to specify the dates for November and December. How can we append these entries to the already created dictionary?
Method 1: Simply assign values to new keys
The first method is simplicity itself. We simply specify what the new (key, value) pair should be in a new line of code, like so:
If we now tried print(calendar_days), we get:
Method 2: Use the update() method
This second method is useful if you desire to append multiple key-value pairs at once. Here, we use the update() method. Here's how you would add two months to the calendar (assuming we start with the first dictionary definition that has months only till October):
In this case, new_months is another dictionary containing the months we want to add. The update() method merges new_months into calendar_days, adding the new key-value pairs. The output will thus be:
Thus in summary, the two easy ways to append to a dictionary are simply to specify the new entries or to use the update() method to combine two dictionaries.
What happens if the keys overlap between the two entries being added? Because dictionaries are mutable, the old values will simply get rewritten. For instance, try the following code:
Note that we have removed December from the new months and updated the number of days for May to 32 (this is obviously not a reflection of the real month of May, but is a good illustration for our purposes). The output will be:
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.