Python’s Dictionary datatype is a class, which means it has methods directly associated with it to make working with that data easier.
The clear()
method allows you to empty the dictionary of all of it’s data.
phonebook = {'James':'555-1234','Mary':'555-5678','John':'555-2468','Martha': '555-1357'}
print(phonebook)
phonebook.clear()
print(phonebook)
The get()
method works similarly to the [key], where you get the value of the key. The main difference is, you can define a default value in case that value isn’t set.
For example, you might have a phone directory of people with a direct line to your organization, but if they don’t have a direct line, you have to call through the switchboard.
It follows the general form of:
dictionary.get(key, default_value)
Here’s an example:
phonebook = {'James':'555-1234','Mary':'555-5678','John':'555-2468','Martha': '555-1357'}
print(phonebook.get('James', '555-9999'))
print(phonebook.get('Jennifer', '555-9999'))
print(phonebook.get('Jessie', 'User not found.'))
The keys()
method returns a list of all of the keys in the dictionary. You can then loop over it, or use it as a list if needed.
The values()
method returns a list of all of the values stored within the dictionary.
Both the keys()
and values()
methods can be obtained with a loop, however, this is a little easier since they are built into the Python language.
The pop()
method returns an element of a dictionary, and removes it at the same time. This is quite different from how a pop() operation occurs on a stack object, and shouldn’t be confused if you are familiar with stacks.
phonebook = {'James':'555-1234','Mary':'555-5678','John':'555-2468','Martha': '555-1357'}
print(phonebook)
print(phonebook.pop('Mary'))
print(phonebook)
The popitem()
method is similar to pop()
, however, instead of popping a specific element, it returns and removes a random element from the dictionary.
Since it is removing an unknown element, it returns two pieces of data, a key and a value. The general form looks like:
key, value = dictionary.popitem()
Python’s Dictionary Methods was originally found on Access 2 Learn