Dictionary Operations¶
For this section, let’s begin by creating and displaying the dictionary roman_numerals. We intentionally provide the incorrect value 100 for the key ‘X’, which we’ll correct shortly:
roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100}
Accessing Values via Keys:
Let’s get the value associated with the key 'V':roman_numerals['V']
Updating the Value of an Existing Key-Value Pair:
You can update a key’s associated value in an assignment statement, which we do here to replace the incorrect value associated with the key 'X':roman_numerals['X'] = 10
Adding a New Key-Value Pair:
Assigning a value to a nonexistent key inserts the key–value pair in the dictionary:roman_numerals['L'] = 50
String keys are case sensitive. Assigning to a nonexistent key inserts a new key–value pair. This may be what you intend, or it could be a logic error.
Removing a Key-Value Pair
You can delete a key–value pair from a dictionary with the del statement:Del roman_numerals['III']
You also can remove a key–value pair with the dictionary function pop
, which returns the value for the removed key:
roman_numerals.pop('X')
Accessing a Nonexistent Key
Accessing a nonexistent key results in a KeyError. You can prevent this error by using the dictionary function `get`, which normally returns its argument’s corresponding value. If that key is not found, `get` returns None. [13]. If you specify a second argument to get, it returns that value if the key is not found:roman_numerals.get('V')
Testing Whether a Dictionary Contains a Specified Key:
Operators in and not in can determine whether a dictionary contains a specified key:'V' in roman_numerals
'III' not in roman_numerals
Comparing Dictionaries:
The comparison operators == and != can be used to determine whether two dictionaries have identical or different contents. An equals (==) comparison evaluates to True if both dictionaries have the same key–value pairs, regardless of the order in which those key–value pairs were added to each dictionary:dictionary1 = {1: 'Red', 2: 'Orange', 3: 'Yellow'}
dictionary2 = {2: 'Orange', 3: 'Yellow', 1: 'Red'}
print(dictionary1 == dictionary2) # Displays True