Built-in Dictionary Methods
Some of the methods you learned about strings, lists, and tuples also work with dictionaries. For example, the
in (or
not in) method allows you to determine if a particular key exists. in the dictionary.
And also allows you to go through all the keys of the dictionary.
for key in dict_country:
print(key)
You can also iterate over key-value pairs using the items() method.
for key, value in dict_country.items():
print(key, value)
Other commonly used methods are listed in the table.
| Name |
Method |
Description (example) |
| dictionary size |
len() |
returns the number of elements in the dictionary
len(dict_country)
|
| updating dictionary |
update() |
allows you to update several dictionary pairs at once
dict_country.update({'Russia': 'Moscow', 'Armenia': 'Yerevan'})< /pre>
|
| get value by key |
get() |
allows you to get the value by the specified key. Can be used to check if a particular key exists in a dictionary
dict_country.get('Russia') # returns value by key,
# if there is no such key, it will return None
dict_country.get('Russa', 0) # if there is no Russia key, it will return 0
# (instead of 0, you can set any value
|
| remove key |
pop() |
The pop() method removes a key and returns its corresponding value.
dict_country.pop('Bahamas')
|
| dictionary keys |
keys() |
The keys() method returns a collection of keys in a dictionary.
dict_country.keys()
|
| dictionary values |
values() |
The Method values() returns a collection of values in a dictionary.
dict_country.values()
|
| dictionary pairs |
items() |
The items() method returns a collection of values in a dictionary.
dict_country.items()
|