Python.  Dictionaries. Basic concepts. Specifications. Creating dictionaries. Accessing dictionary values

 Dictionaries. Basic concepts. Specifications. Creating dictionaries. Accessing dictionary values


Search other websites:

1. Features of dictionaries. The advantages of using

In Python, you can use dictionaries. Dictionaries are a built-in data type that is an associative array or hash and is based on mapping pairs of type (key: value).

Advantages of using dictionaries:

  • using dictionaries, you can develop effective data structures;
  • for dictionaries do not need to manually write data search algorithms, as these operations have already been implemented;
  • dictionaries may contain combined data in the form of records;
  • dictionaries are effective in representing sparse data structures.

The main characteristics of dictionaries are as follows:

  • in dictionaries, access to items is performed by key, not by index. Dictionaries define the relationship of key:value pairs. The key accesses the value. If the dictionary implements access to the value by index, then in this case the index is a key, not an offset from the beginning;
  • dictionaries represent unordered collections of arbitrary objects. In dictionaries, items (keys) are stored in an undefined order. The order of formation of items in the dictionary is determined by the interpreter. This is necessary to provide quick search;
  • dictionaries have a variable length. The number of items in the dictionary can be increased or decreased;
  • heterogeneity – dictionaries can contain objects of any type;
  • arbitrary number of attachments – dictionaries have the ability to create an arbitrary number of attachment levels, since dictionaries can contain lists, other dictionaries, etc .;
  • dictionaries are classified as mutable objects. Therefore, in dictionaries it makes no sense to use operations that have a fixed sequence of items (for example, concatenation);
  • dictionaries are object reference tables or hash tables and refer to the mapping objects. This means that in dictionaries, objects map (represent) keys to a value.


2. Differences between dictionaries and lists

The following main differences exist between dictionaries and lists:

  • lists are ordered collections; dictionaries are not ordered collections;
  • in lists, items are retrieved using an offset that determines the position of the item in the list. In dictionaries, items are retrieved using a key;
  • unlike lists, dictionaries do not support operations on sequences (for example, concatenation, get a slice, etc.);
  • lists are arrays of references to objects. Dictionaries are arrays of unordered tables of references to objects that support access to objects by key.


3. Operations and dictionary processing methods

Python has a huge variety of operations and methods for processing dictionaries. All of these tools are briefly listed here:

  • standard len() method – determines the number of items in the list;
  • operation D[key] – access to the dictionary item D by the value of the key;
  • operation del – delete an item by key;
  • operations in, not in – determining the presence or absence of a key in the dictionary;
  • iter() method – get an iterator using dictionary keys;
  • clear() method – remove all items from the dictionary;
  • copy() method – return a copy of the dictionary;
  • dict.fromkeys() method – create a new dictionary from keys and values;
  • get() method – get the value by key;
  • method items() – return the representation of dictionary items;
  • keys() method – get a new view of dictionary keys;
  • method pop() – delete items from the dictionary with a return value;
  • popitem() method – pulling an arbitrary pair of key:value pairs from a dictionary;
  • setdefault() method – set the default item;
  • update() method – updates a dictionary using a given list of key:value pairs;
  • method values() – get a list of values from the dictionary.

In more detail, the use of the above operations and methods can be studied in the topics:


4. Features of representation of keys by numeric types

In dictionaries, numeric types can be used as keys: integer or real (floating point). In the case of the representation of keys by numerical types, the following features can be distinguished:

  • when searching for the desired key value, a simple comparison operation is used. If the value of different numeric types is specified as a key, for example 1 and 1.0, then such values are considered interchangeable (refer to the same element of the dictionary);
  • representation of a key by a floating-point numeric type is not recommended, since the value of these types is approximate. If you need to specify a numeric type as a key, then it is advisable to use integer numeric types for this.


5. What values cannot be used as keys?

You cannot use mutable object types as keys. For example, lists, dictionaries, and other mutable types cannot be used as keys. However, these mutable types can be used as values.


6. What are the ways to create a dictionary?

In Python, you can use one of the following methods to create a dictionary:

  • with the help of the assignment operator = and curly braces, in which key:value pairs are placed through a comma;
  • using the dict() constructor of the dict class.


7. Creating a dictionary using the assignment operator =. Examples

A dictionary can be created in a convenient (natural) way using the assignment operator =.

# Creating a dictionary using assignment operator
# 1. Empty dictionary
A = {}
print('A = ', A)

# 2. Dictionary of 3 items
# 2.1. Contains integer keys and value strings
B = { 1:'Mon', 2:'Tue', 3:'Wed', 4:'Thu',
5:'Fri', 6:'Sat', 7:'Sun' }
print('B = ', B)
print('B[2] = ', B[2]) # B[2] =   Tue

# 2.2. Contains string keys and real values
C = { 'Pi':3.1415, 'Exp':2.71 }
print('C = ', C)
print('C[Exp] = ', C['Exp']) # C[Exp] =   2.71

# 2.3. A dictionary that contains sets of values
D = { 'Table1':[ 1, 2, 4], 'Table2':[ 8, -2, 2.33] }
print('D = ', D)
print('D[Table1] = ', D['Table1']) # D[Table1] = [1, 2, 4]
print('D[Table2] = ', D['Table2']) # D[Table2] = [8, -2, 2.33]

The result of the program

A = {}
B = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun'}
B[2] = Tue
C = {'Pi': 3.1415, 'Exp': 2.71}
C[Exp] = 2.71
D = {'Table1': [1, 2, 4], 'Table2': [8, -2, 2.33]}
D[Table1] = [1, 2, 4]
D[Table2] = [8, -2, 2.33]


8. Creating a dictionary using the dict() constructor. Example

A dictionary can be created using one of the dict() constructors, which are implemented in the dict class. According to the Python documentation in the dict class, 3 constructors are used, which have the following general form

dict(mapping, **keyword_arg)
dict(iterable, **keyword_arg)


  • keyword_arg is an optional key argument. If the constructor is called without a key argument (for example, dict()), an empty dictionary is created. If several key arguments are specified in the constructor, they are separated by a comma (** symbols are used in the general form of the constructor);
  • mapping – the mapping object on the basis of which the dictionary is created;
  • iterable – iterated object on the basis of which the dictionary is created.

Depending on the arguments, the Python interpreter invokes the corresponding constructor. In all constructors, the first object of each item becomes the key, the second becomes the corresponding value.

If the key occurs more than once, then the last value is accepted which set for this key.

Example. It demonstrates how to create dictionaries in many ways.

# Creating a dictionary using the dict() constructor
# 1. A kind of constructor dict(**keyword_arg)
# 1.1. Create an empty dictionary
A = dict()
print('A = ', A) # A = {}

# 1.2. Create a list
# {'Winter': 1, 'Spring': 2, 'Summer': 3, 'Autumn': 4}
SEASONS = dict( Winter=1, Spring=2, Summer=3, Autumn=4)
print('SEASONS = ', SEASONS)

# ---------------------------------------------------
# 2. A kind of constructor dict(mapping, **keyword_arg)
# 2.1. Using the zip() function
DAYS = [ 1, 2, 3 ]
DAYS_NAMES = [ 'Mon', 'Tue', 'Wed' ]
print(DICT_DAYS) # {1: 'Mon', 2: 'Tue', 3: 'Wed'}

# 2.2. Using (key:value) pairs
DICT_DAYS = dict([(1,'Mon'), (2,'Tue'), (3,'Wed')])
print(DICT_DAYS) # {1: 'Mon', 2: 'Tue', 3: 'Wed'}

# ---------------------------------------------------
# 3. A kind of constructor dict(iterable, **keyword_arg)
#   The use of constructor
B = dict({1:'Mon', 2:'Tue', 3:'Wed'})
print('B = ', B) # B = {1: 'Mon', 2: 'Tue', 3: 'Wed'}

The result of the program

A = {}
SEASONS = {'Winter': 1, 'Spring': 2, 'Summer': 3, 'Autumn': 4}
{1: 'Mon', 2: 'Tue', 3: 'Wed'}
{1: 'Mon', 2: 'Tue', 3: 'Wed'}
B = {1: 'Mon', 2: 'Tue', 3: 'Wed'}


9. How is a value accessed by its key?

In the dictionary, if a key is known, then access to the value by this key can be obtained using the operation []. n the same way, you can change the value if you know the key that corresponds to this value.

For example

# Access to the value in the dictionary
# 1. Create a list
# {'Winter': 1, 'Spring': 2, 'Summer': 3, 'Autumn': 4}
SEASONS = dict( Winter=1, Spring=2, Summer=3, Autumn=4)

# 2. Print the value by the key 'Spring'
value = SEASONS['Spring'] # value =   2

# 3. Change the value in the dictionary by its key
# The dictionary with numbers and names of rooms is set
D = { 233:'Lecture hall', 234:'Laboratory' }

# Change 'Laboratory' на 'Programming laboratory'
D[234] = 'Programming laboratory'


10. Examples of avoiding access errors on a nonexistent key

When working with dictionaries, a situation is possible when access occurs by a key that is not in the dictionary. In this case, an error occurs in the program and a KeyError exception is thrown.

To avoid an access error with a key that does not exist, you can use one of three methods:

  • pre-check the presence of the key using the if construct;
  • use the try-except block to handle a KeyError exception;
  • use the get() method, which, in the case of a non-existent key, returns the default value.

The example demonstrates all three methods.


# Dictionaries Avoid access by non-existent key
# Source dictionary
Days = { 1:'Mon', 2:'Tue', 3:'Wed',
         4:'Thu', 5:'Fri', 6:'Sat', 7:'Sun' }

# 1. Trying to access a nonexistent day
# day = Days[8] # a KeyError exception is thrown: 8

# 2. Method 1. Addressing a nonexistent day,
#    using the if statement
day = int(input("Enter day: "))
if day in Days:    
    print("day = ", Days[day])
    print("1. Using if statement: Error.")

# 3. Method 1. Addressing a nonexistent day,
#    using the try-except construct
    print('day = ', Days[day])
except KeyError:
    print('2. Using try-except statement: Error.')

# 4. Method 1. Addressing a nonexistent day,
#    using get() method
print('3. Using get() method: ', Days.get(day))


11. Examples of nested dictionaries

Dictionaries may contain other nested dictionaries as values. For example:

# Nested dictionaries
# Example 1.
# Internal dictionary
Worker_Type = { 'Manager':1, 'SupportStaff':2 }

# External dictionary
# {'Worker': {'Manager': 1, 'SupportStaff': 2}}
Worker_Dict = { 'Worker' : Worker_Type }

# Example 2.
Figures = { 'Figure' : { 1:'Circle', 2:'Triangle', 3:'Rombus' } }

The result of the program

{'Manager': 1, 'SupportStaff': 2}
{'Worker': {'Manager': 1, 'SupportStaff': 2}}
{'Figure': {1: 'Circle', 2: 'Triangle', 3: 'Rombus'}}


Related topics