
Dictionaries
A Python dictionary is a built-in data structure that is used to store and manage collections of data in the form of key-value pairs, e.g. {key1: value1, key2: value2, key3: value3, ...}
. Each key in a dictionary is associated with a corresponding value. They are created using curly braces {}
or the dict()
constructor.
Properties of Dictionaries
- Unordered: Dictionaries are unordered collections of key-value pairs. The order of elements is not guaranteed in Python versions prior to Python 3.7, but from Python 3.7 onward, dictionaries maintain the insertion order of elements.
- Mutable: Dictionaries are mutable, which means you can add, modify, or remove key-value pairs after creating the dictionary.
- Keys are Unique: Keys in a dictionary are unique. Each key can only have one associated value. If you try to add a duplicate key, the new value will overwrite the existing one.
- Indexable: You can access the values in a dictionary by specifying the key associated with the target value.
Example
The dictionary below contains three key-value pairs.
The keys are: name, age, city.
The values are: Alice, 30, New York.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Methods of Dictionaries
get()
Function
The get()
function returns the value associted with the specified key, or the default value if the key is not found.
Syntax: dictionary.get(key, default)
- key: the specific key name associated with the target value.
- default: a self-defined value to return if the key is not found.
# Create a dictionarysample_dict = {'name': 'John', 'age': 28, 'hobbie': 'hiking'}
# Get the value 'hiking', and set the default to 'Unknown' hobbie = sample_dict.get('hobbie', 'Unknown')print(hobbie)
# Get the value 'John'name = sample_dict.get('name', 'Unknown')print(name)
# Using a non-exisiting key returns the default value print(sample_dict.get('city', 'Unknown'))
Output:
hiking
John
Unknown
Additionally, values can be accessed using []
. Unlike get()
method, which allows setting a default return value, using []
will raise a "KeyError" if the key doesn't exist in the dictionary.
Example of using []
to access values
# Get the value 'hiking' hobbie = sample_dict['hobbie']print(hobbie)
# Get the value 'John'name = sample_dict['name']print(name)
Output:
hiking
John
Using a non-existent key through []
will raise a KeyError.
# Using a non-existing key raises KeyErrorprint(sample_dict['city'])
Output:
---------------------------------------------------------------------------KeyError Traceback (most recent call last)Input In [21], in <cell line: 2>() 1 # Using a non-existing key raises KeyError----> 2 print(sample_dict['city'])
KeyError: 'city
keys()
Function
The keys()
function returns an object containing all keys in the dictionary.
# Create a dictionary named "student"student = { "first_name": "John", "last_name": "Doe", "age": 20, "grade": "A", "courses": ["Math", "English", "Science"]}
# Get all keys in the dictionarykeys = student.keys()print(keys)
Output:
dict_keys(['first_name', 'last_name', 'age', 'grade', 'courses'])
values()
Function
The values()
function returns an object containing all values in the dictionary.
# Get all values in the dictionaryvalues = student.values()print(values)
Output:
dict_values(['John', 'Doe', 20, 'A', ['Math', 'English', 'Science']])
items()
Function
The items()
function returns an object containing all key-value pairs (tuples) in the dictionary.
# Get all key-value pairs in the dictionaryitems = student.items()print(items)
Output:
dict_items([('first_name', 'John'), ('last_name', 'Doe'), ('age', 20), ('grade', 'A'), ('courses', ['Math', 'English', 'Science'])])
len()
Function
The len()
function returns the number of key-value pairs in the dictionary.
count = len(student)print(count)
Output:
5
update()
Function
The update()
function updates the dictionary with key-value pairs from another dictionary.
# Create a dictionarysample_dict = {'name': 'John', 'age': 30}
# Update the dictionary by adding the city informationsample_dict.update({'city': 'New York'})print(sample_dict)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
# Update the dictionary by changing the age valuesample_dict.update({'age': '31'})print(sample_dict)
Output:
{'name': 'John', 'age': '31', 'city': 'New York'}
pop()
Function
The pop()
function removes the specified key and its associated value from the dictionary and returns the value.
# Create a dictionarysample_dict = {'brand': 'CocoCode Academy', 'type': 'learning website'}print(sample_dict)
# Remove the type from the dictionarysample_dict.pop('type')print(sample_dict)
Output:
{'brand': 'CocoCode Academy', 'type': 'learning website'}
{'brand': 'CocoCode Academy'}
clear()
Function
The clear()
function removes all key-value pairs from the dictionary, making it empty.
# Create a dictionarysample_dict = {'brand': 'CocoCode Academy', 'type': 'learning website'}
# Remove the type from the dictionarysample_dict.clear()print(sample_dict)
Output:
{}