Python: Dictionary

A dictionary in Python is a mutable data type, similar to a list, that can store a collection of objects of different types. Essentially, it represents an associative array. Each element has a key instead of a number, meaning elements are stored in pairs of "key:value". The general form of a dictionary is:

{< key 1>:< value 1>, < key 2>:< value 2>, ..., < key N>:< value N>}

{1: 'Nick', 'age': 20}

Dictionary values are stored in unsorted order. Dictionaries store references to objects, not the objects themselves.

Creating a Dictionary

To work with a dictionary, you need to create it. There are several ways to do this. Using a literal. Empty dictionary:

Code: Creating a Dictionary

# create dict using literal
a = {}
print(a)
# {}

# Dictionary with given keys and values
a = {'name':'Nick', 'age':20}
print(a)
# {'age': 20, 'name': 'Nick'}

'''
Dynamically creating a dictionary
Before adding elements, 
you must create an empty dictionary
'''
a = {}
a['name'] = 'Nick'
a['age'] = 20
print(a)
# {'name': 'Nick', 'age': 20}

'''
Function dict()
The keys must be there strings
Don't put the key in quotes
'''
a = dict(name='Nick', age=20, сity='London')
print(a)
# {'name': 'Nick', 'age': 20, 'сity': 'London'}


'''
Create a dictionary from two sequences
using the zip() function
'''
a = ['name', 'age', 'city']
b = ['Anna', 22, 'Paris']
c = dict(zip(a, b))
print(c)
# {'name': 'Anna', 'age': 20, 'сity': 'Paris'}

'''
Create a dictionary using the fromkeys function
Creates a dictionary from a list of keys with empty values
'''
a = {}.fromkeys(['name', 'age'])
print(a)
# {'name': None, 'age': None} 

'''
Create a dictionary and after the comma
specify the default value for all fields.
This method does not allow you to specify 
different default values for each key.
The default value for each key will be the same list.
'''
a = {}.fromkeys(['name', 'age'], 20)
print(a)
# {'name': 20, 'age': 20} 
a = {}.fromkeys(['name', 'age'], ['Nick', 20])
print(a) 
# {'age': ['Nick', 20], 'name': ['Nick', 20]}

'''
Dictionary generator (comprehension)
'''
a = {i: i**2 for i in range(5)}
print(a)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

'''
Filling a dictionary from the keyboard using a generator.
'''
a = {input('Enter key: '):input('Enter value: ') for i in range(2)}
print(a)

# Enter value: Nick
# Enter key: name
# Enter value: 20
# Enter key: age
# {'age': '20', 'name': 'Nick'}

Getting data from the dictionary

The print() function is used to print the entire dictionary. If you need to display a specific dictionary element, then you need to know its key. You can display an element by specifying its key in square brackets. If we try to get a value from a dictionary using a non-existent key, we will receive an error.

Code: Getting value from the dictionary

a = {i: i**2 for i in range(5)}

print(a)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

print(a[2])
# 4

print(a[16])
# KeyError: 16

Updating data in a dictionary

You can update data in the dictionary by key by specifying the pair: key:new value. If such a key is already in the dictionary, then the corresponding value will change, and if there is no such key, then a new key:value pair will be added.

If the key is already in the dictionary, its value will change.

If the key is not in the dictionary, a new value will be added.

Code: Updating values in a dictionary

a = {'name': 'Nick', 'age': 20}
a['name'] = 'Alex'

print(a)
# {'name': 'Alex', 'age': 20}


a = {'name': 'Alex', 'age': 20}
a['city'] = 'London'

print(a)
# {'name': 'Alex', 'age': 20, 'city': 'London'}

Removing Dictionary Items

When performing the delete procedure, you can delete an element by key, clear the entire dictionary, or delete the entire dictionary along with its contents. For This procedure uses the del operator.

Code: Removing dictionary elements

'''Delete by key'''
a = {'name': 'Nick', 'age': 20, 'city': 'London'}
del a['age']

print(a)
# {'name': 'Nick', 'city': 'London'}

'''
Clearing the dictionary
'''
a = {'name': 'Alex', 'age': 20}
a.clear()

print(a)
# {}

'''
Delete a dictionary
'''
a = {'name': 'Nick', 'age': 20}
del a

print(a)
# NameError: name 'a' is not defined

Basic Dictionary Functions and Methods

In the description of all functions we will use the same dictionary:

a = {'name': 'Nick', 'age': 20, 'city': 'London'}

Code: Dictionary Functions and Methods

a = {'name': 'Nick', 'age': 20, 'city': 'London'}

'''
len() - returns the number of entries in the dictionary
'''
print(len(a))
# 3


'''
clear() - clears the dictionary
'''
a.clear()
print(a)
# {}


'''
 copy() - creates a copy of the dictionary
'''
b = a.copy()
print(b)
# {'name': 'Nick', 'age': 20, 'city': 'London'}


'''
get(key, default) - returns the value by key. 
If there is no such key, then returns the value
specified in the default parameter.
By default it is equal None
'''
print(a.get('name')) 
# 'Nick'

print(a.get('country'))
# None

print(a.get('town', 'Key not found'))
# Key not found


'''
items() - returns all key: value pairs
'''
print(a.items()) 
# dict_items([('name', 'Nick'), ('age', 20), ('city', 'London')])


'''
keys() - returns the keys in the dictionary
'''
print(a.keys())
# dict_keys(['name', 'age', 'city'])


'''
values() - returns all values in the dictionary
'''
print(a.values()) 
dict_values(['Nick', 20, 'London'])


'''
pop(key[, default]) – removes the key from the dictionary
and returns the value. If the key is not in the dictionary,
returns the value specified in default, and if default
is not specified, then raises an exception
'''

print(a.pop('age'))
# 20
print(a)
{'name': 'Nick', 'city': 'London'}

print(a.pop('was born', 'Element missing'))
# Element missing

print(a.pop('was born'))
# KeyError: 'was born'


'''
popitem() – removes from the dictionary and returns
the first key:value pair. Attention, the dictionary
is not ordered, and after adding the order of the elements
can change. If the dictionary contains no elements,
it returns exception.
'''

a = {'name': 'Nick', 'age': 20, 'city': 'London'}
b = a.popitem() 

print(b)
# ('city', 'London')

print(a) 
{'name': 'Nick', 'age': 20}

Looping through dictionary items using a loop

You can iterate through all the elements of a list using a for loop, but Python dictionaries are not sequences. As an example, let's display the elements of the dictionary two methods.

The first method uses the keys() method, which returns a list of all keys dictionary.

Second method: specify the dictionary as a parameter. At each iteration of the loop will return a key with which you can get inside the loop the value corresponding to this key.

Code: Looping through dictionary elements

a = {'name': 'Nick', 'age': 20, 'city': 'London'}


for i in a.keys():
    print(i, '-', a[i])

# name - Nick
# age - 20
# city - London

for i in a:
    print(i, '-', a[i]) 

# name - Nick
# age - 20
# city - London

Links: python documentation


[1] Dictionary - methods


[2] Dictionary - introduction to dictionaries