Dictionaries
A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.
Creating a Dictionary
To create a dictionary we use curly brackets, {}.
# empty one empty_dicto = {}
dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
Example:
book = { 'name':'The Heart Principle', 'author':'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], }
The dictionary above shows that a value could be any different data type.
- string
- boolean
- list
- tuple
- set or a dictionary.
Dictionary Length
It checks the number of key: value
pairs in the dictionary.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(len(dicto)) # 4
Example:
book = { 'name':'The Heart Principle', 'author':'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } print(len(book)) # 4
Accessing Dictionary Items
We can access Dictionary items by referring to its key name.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dicto['key1']) # value1 print(dicto['key4']) # value4
Example:
book = { 'name':'The Heart Principle', 'author':'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } print(book['name']) # The Heart Principle print(book['author']) # Helen Hoang print(book['genres'][1]) # Fiction
- Accessing an item by key name raises an error if the key does not exist.
- To avoid this use get method.It returns None, which is a NoneType object data type, if the key does not exist.
book = { 'name':'The Heart Principle', 'author':'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } print(book.get('name')) # The Heart Principle print(book.get('author')) # Helen Hoang print(book.get('genres')) # ['Romance novel', 'Fiction', 'Contemporary romance']
Adding Items to a Dictionary
We can add new key and value pairs to a dictionary
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dicto['key5'] = 'value5'
Example:
book = { 'name':'The Heart Principle', 'author':'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } book['genres'].append('something')
Modifying Items in a Dictionary
We can modify items in a dictionary
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dicto['key1'] = 'value-one'
Example:
book = { 'name': 'The Heart Principle', 'author': 'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } book['name'] = 'Beautiful Country: A Memoir'
Checking Keys in a Dictionary
We use the in
operator to check if a key exist in a dictionary.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print('key2' in dicto) # True print('key5' in dicto) # False
Getting Dictionary Keys as a List
The keys()
method gives us all the keys of a a dictionary as a list.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} keys = dicto.keys() # dict_keys(['key1', 'key2', 'key3', 'key4'])
Getting Dictionary Values as a List
The values
method gives us all the values of a a dictionary as a list.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} values = dicto.values() print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
Deleting a Dictionary
If we do not use the dictionary we can delete it completely
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} del dicto
Removing Key and Value Pairs from a Dictionary
pop(key)
: removes the item with the specified key name:popitem()
: removes the last itemdel
: removes an item with specified key name
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dicto.pop('key1') # removes key1 item dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dicto.popitem() # removes the last item del dicto['key2'] # removes key2 item
Example:
book = { 'name': 'The Heart Principle', 'author': 'Helen Hoang', 'published': '31 August 2021', 'genres': ['Romance novel', 'Fiction', 'Contemporary romance'], } book.pop('name') # Removes the name of the book del book['published'] # Removes the published date of the book
Changing Dictionary to a List of Items
The items()
method changes dictionary to a list of tuples.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dicto.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])
Clearing a Dictionary
If we don’t want the items in a dictionary we can clear them using clear()
method.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dicto.clear()) # None
Copy a Dictionary
We can copy a dictionary using a copy()
method.Using copy we can avoid mutation of the original dictionary.
# syntax dicto = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dicto_copy = dicto.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}