8. Dictionaries

by Alex
8. Dictionaries
  1. Structure. The dictionary consists of key-value pairs, which are separated by commas. Within each pair, the value is separated from the key by a colon. The easiest way to understand the syntax is to use an example.
  2. Composite structure. A dictionary is a useful composite data structure that can store different types of data. Similar to a list, it can be called a sequence of data.
  3. No order. Unlike lists and tuples, dictionaries have no specific order. You can imagine that pairs of key and value are jumbled in a bag. And there is no first, second or last element in it – they just exist at random. This structure is aimed at increasing performance and assumes access to the value by the key.

Where is it used?

Dictionaries are a common data structure in Python. They are used in a wide variety of situations. Here are some of the methods and functions of dictionaries:

  • .keys() – used to display the keys of the dictionary.
  • .items() – used to create tuples with keys and values.
  • .get() – method to get value by key.
  • .clear() – clear the dictionary.
  • .copy() – copy the whole dictionary.
  • .len() – get the length of the dictionary.
  • type() – get the type.
  • min() – get the key with the minimum value.
  • max() – get the key with the maximum value.

Recommendations for working with dictionaries

  1. Dictionaries are created using curly braces.
  2. Pairs of keys and values are separated by commas.
  3. Keys and values are separated by a colon
  4. Keys in the dictionary can only be strings, integers or floating-point numbers. But values can be of any type
  5. It’s important not to forget to use quotes for the key string

Next is an example of a dictionary, where strings are used as keys, and integers are used as values.

>>> p_ages = {"Andrey": 32, "Victor": 29, "Maxim": 18}
>>> print(p_ages)
{"Andrei": 32, "Viktor": 29, "Maxim": 18}

All strings in the dictionary are enclosed in quotes. In the following example the keys are already integers, and the values are strings.

>>> p_ages = {32: "Andrew", 29: "Victor", 18: "Maxim"}
>>> print(p_ages)
{32: "Andrew", 29: "Victor", 18: "Maxim"}

This time the quotes should be used for the values, which are represented here as strings. The values of the dictionary can be accessed by its keys. So, to get the value of the key “Victor” you need to use the following syntax:

>>> p_ages = { "Andrei": 32, "Victor": 29, "Maxim": 18}
>>> p_ages["Maxim"]
18
>>> p_ages["Andrei"]
32

Merge and Update

Beginning with Python 3.9, the language has new operators that make merging dictionaries easier.

  1. Merge(|): this operator allows you to combine two dictionaries with one |.
  2. Update(|=): using this operator you can update the first dictionary with the value of the second (with the type dict)

Here are the main differences between the two operators:

  • “|” creates a new dictionary by combining two dictionaries, and “|=” updates the first dictionary.
  • The operator merge (|) simplifies the process of merging dictionaries and working with their values.
  • The update operator (|=) is used to update the dictionaries.
>>> dict1 = {"x": 1, "y":2}
>>> dict2 = {"a":11, "b":22}
>>> dict3 = dict1 | dict2
>>> print(dict3)
{"x":1, "y":2, "a":11, "b":22}
>>> dict1 = {"x": 1, "y":2}
>>> dict2 = {"a":11, "b":22}
>>> dict2 |= dict1
>>> print(dict2)
{"x":1, "y":2, "a":11, "b":22}

Note: if there are overlapping keys (and Python dictionaries can only have one unique key), the key of the second dictionary will remain, and the first one will simply be replaced.

Function #1: .keys()

.keys() is a handy method that returns all the keys in the dictionary. Next, let’s look at an example using the keys method.

>>> p_ages = { "Andrei: 32, "Victor": 29, "Maxim": 18}
>>> print(p_ages.keys())
dict_keys(['Andrei', 'Victor', 'Maxim'])

Function #2: .items()

.items() returns a list of tuples, each of which is a key-value pair. The usefulness of this function will become clear at a later stage in your work as a programmer, but for now it is sufficient to simply memorize this function.

>>> p_ages = { "Andrei": 32, "Victor": 29, "Maxim": 18}
>>> a = p_ages.items()
>>> print(a)
dict_items([('Andrey', 32), ('Victor', 29), ('Maxim', 18)])

The .items() method comes in handy when you need to use indexing to access the data.

Function #3: .get()

.get() is a useful method for getting values from the dictionary by key. Let’s access age using the .get() method.

>>> p_ages = { "Andrei: 32, "Victor": 29, "Maxim": 18}
>>> print(p_ages.get("Andrei"))
32

Function #4: .clear()

The .clear() method clears the dictionary of all elements.

>>> p_ages = {"Andrei: 32, "Victor": 29, "Maxim": 18}
>>> p_ages.clear()
>>> print(p_ages)
{}

Function #5: .copy()

The .copy() method returns a copy of the dictionary.

>>> p_ages = {"Andrei: 32, "Victor": 29, "Maxim": 18}
>>> print(p_ages.copy())
{"Andrei": 32, "Viktor": 29, "Maxim": 18}

Function #6: len()

The len() method returns the number of elements in the dictionary.

>>> p_ages = {"Andrei: 32, "Victor": 29, "Maxim": 18}
>>> print(len(p_ages))
3

Good to know

  1. The get() method is more advanced compared to the get value by key approach. If you add a second parameter to the method, it returns the value passed when the key is not found. If you don’t specify the second parameter, it will return None.
  2. If you try to use the new operators (| and |=) in older versions of python, you will get TypeError. This includes dict comprehension.
>>> p_ages = { "Andrei: 32, "Victor": 29, "Maxim": 18}
>>> print(p_ages.get("Mikhail", "Not found"))
Not found
>>> print(p_ages.get("Andrei", "Not found"))
32

Problems for the lesson

Try solving the problems for this lesson to consolidate knowledge. 1. Derive the meaning of age from the person dictionary.

# this code
person = {"name": "Kelly", "age":25, "city": "new york"}
# required output:
# 25

2. The values of the dictionary can also be lists. Add the dictionary with keys BMW, VAZ, Tesla and lists of 3 models as values.

# this code
models_data = {..., "Tesla": ["Modes S", ...]}
print(models_data["Tesla"][0])
# output required:
# Modes S
  1. Correct the errors in the code to get the required output.
# this code
d1 = {"a": 100. "b": 200. "c":300}
d2 = {a: 300, b: 200, d:400}
print(d1["b"] == d2["b"])
# required output:
# True

File with all the assignments: https://gitlab.com/PythonRu/python-dlya-nachinayushih/-/blob/master/lesson_8.py.

Vocabulary quiz

Take the quiz for this lesson to test your knowledge. The test has 5 questions and the number of attempts is unlimited. How to get the value of “marks” of the dictionary student = {“name”: “Emma”, “class”: 9, “marks”: 75} student.get(3) student(“marks”) None of them are correct student.get(2) Continue How to create an empty dictionary d = dict{} All ways are correct d = {} d = {:} Continue What data types can be dictionary keys int, list, str str, int, tuple Any data type float, list, tuple int, float, str Continue to What will this code print?

p = {"name": "Mike", "salary": 8000}
print(p.get("age"))

Error “age” 28 None Continue to How to get “d”:

sample = {"1":["a", "b"], "2":["c", "d"]}

sample[“2”][2] sample[“2][1] sample[“2”][1] sample[2][2] Continue Continue to Share results via Facebook Twitter VK Repeat If you find a mistake, a typo, or know how to improve this lesson, email. It can be found at the bottom of the site.

The end. What to do next?

This short series is an introduction to python programming. If you’ve solved problems, passed tests, dealt with bugs and haven’t lost motivation to become a developer, it’s worth continuing! You can learn the basics, for example on free courses from Netology or practice on Skillbox webinars. To go to the next level, write your own program: a calculator, a game, an api. On your own or with the support of mentors from Twitter and EPAM on the Python Developer Profession program.

Related Posts

LEAVE A COMMENT