Зачем нужны словари в python
Перейти к содержимому

Зачем нужны словари в python

  • автор:

# Словари

До сих пор вы хранили данные в списках. Например, есть список друзей пользователя. А список английских слов, которые кто-то из этих друзей хочет выучить, мог бы выглядеть так:

Гораздо удобнее было бы хранить переводы слов с русского на английский, чтобы забытые слова было легко подсмотреть. Для этого в Python есть структура данных dict (от англ. dictionary, «словарь»). Вот как она выглядит:

Словарь оформляется фигурными скобками. Его заполняют пары, записанные через запятую. Первый элемент в паре называется ключ, а второй — значение, они разделяются между собой двоеточием. Русские слова здесь ключи, а их переводы на английский — значения. Когда запрашивают в словаре значение, соответствующее определённому ключу, это называется «доступ по ключу». Так можно получить значение для какого-нибудь ключа и заменить его:

Ключи в словаре похожи на индексы списков. Только индексами выступают натуральные числа, а ключами бывают и числа обоих типов, и строки, и даже булевы значения True и False :

При этом в одном словаре не может быть двух одинаковых ключей.

Чтобы получить все ключи словаря, нужно вызвать метод keys() , а если нужны все значения — метод values() :

Чтобы такие списки использовать в коде, их обычно превращают в строки методом join() :

  1. Научим Виту хранить в словаре записи о друзьях и получать к ним доступ по ключу. Напечатайте на экран город, в котором живет Серёга.
  1. Серёга переехал в Оренбург. Получив по ключу доступ к записи о его городе, отразите этот факт в словаре.

# Расширение словаря

Добавим слов в наш небольшой русско-английский словарь:

Сделать это можно несколькими способами:

Расширяя словарь, имейте в виду, что из нескольких пар с одинаковыми ключами Python видит только одну — ту, что записана или добавлена последней:

# Упражнения

  1. Добавьте в словарь friends ещё две пары ключ-значение, просто дописав их в объявление словаря. Имена друзей и города, в которых они живут, придумайте сами.
  1. После этого напечатайте на экран сообщение "Вот в каких городах живут мои друзья: " и затем названия всех городов словаря, разделённые запятой с пробелом.

# Перебор элементов словаря

Пройти по всем элементам словаря можно циклом for , причем есть несколько вариантов:

Этот способ позволяет пробежать по всем ключам словаря. Обратите внимание, что track здесь — просто название переменной, оно могло быть любым и код отработал бы также. Еще можно пройти отдельно по значениям словаря:

И по ключам и значениям одновременно:

Здесь мы вызвали метод items() — он похож на keys() и values() , но возвращает набор пар ключ-значение, поэтому при переборе мы используем две переменных — track и music_band . Вы можете называть их и по-другому, хоть например song и band .

# Упражнения

  1. Напечатайте о каждом из друзей такое сообщение "<имя друга> живёт в городе <название города>".
  1. В этой задаче вам дан словарь, в котором ключи — имена друзей, а значения — списки любимых песен каждого друга. Напечатайте на экран:
  • Количество любимых песен Димы
  • Все любимые песни Сони через запятую и пробел
  1. Научите Виту собирать словарь friends с нуля. Вам дано два списка: friends_names , имена друзей, и friends_cities — их города. Списки соответствуют друг другу: friends_names[0] живёт в городе friends_cities[0] .

Напечатайте на экран сообщение "Лена живёт в городе <город>" , используя доступ по ключу в словаре friends .

Списки и словари в Python. Разница и смысл

Сейчас постараюсь подробно разобрать списки и словари в Python, объясню смысл их использования, и разберём их различия, а в конце подведём итог.

Списки

Что такое список?

Список это вид переменной у которой сразу несколько значений. Значения могут быть разных типов, например в одном списке может быть как и int(целое число) так и float(число с плавающей точкой) и до кучи к ним ещё и string(строка, буквы). Все данные в списке упорядоченные индексацией.

Как сделать список?

Список в коде создаётся таким путём:

my_list = [данные, через, запятую]

Числа в список забивать нужно без кавычек, а строки с одинарными либо двойными, разницы нет. Но если у вас в строке есть двойные кавычки, то обозначать строку нужно одинарными кавычками, и наоборот. В противном случае, компилятор просто потеряется и выдаст ошибку. Числа с плавающей точкой пишите именно с точкой, хоть за ошибку считаться не будет, но большинство программистов используют именно точку. В списке может быть список, а в нём словарь и так далее…

Как работать с определённым элементом в списке?

Допустим мы хотим вывести на экран определённый элемент из списка. Возьмём 3-й. А запишем в коде мы это так:

Сразу отвечу на вопрос: почему элемент 2-ой, если на самом деле он 3-ий? Давайте вернёмся к школьной программе по математике 5-го класса. Там нам говорят что натуральные числа — числа без плавающей точки, используемые при счёте предметов. 0 и отрицательные числа не являются натуральными числами. Теперь смотрим на список. Данные — они у нас в памяти компьютера, они предметами имеющими какую либо физическую внешность не являются. Соответственно их счёт мы начинаем с нуля. Следственно: 1-ый для нашего понимания — 0-ой для понимания компьютера. Это нужно запомнить.

В прочем работа с определённым элементом из списка идентична работе с переменной, поэтому мы её разбирать не будем.

Как работать с самим списком?

Существует множество функций по работе со списками. Их вы можете найти по ссылке: тык. Сейчас мы разберём поисковые методы.

Таблица поисковых методов

my_list.append(x)

Добавляет элемент в конец списка

list.extend(L)

Расширяет список my_list, добавляя в конец все элементы списка L

my_list.insert(i, x)

Вставляет на i-ый элемент значение x

my_list.remove(x)

Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует

my_list.index(x, [start [, end]])

Возвращает положение первого элемента со значением x (при этом поиск ведется от start до end)

my_list.count(x)

Возвращает количество элементов со значением x

my_list.sort([key=функция])

Сортирует список на основе функции

my_list.reverse()

my_list.copy()

Поверхностная копия списка

my_list.clear()

Сохранение результата выполнения поискового метода в переменную выполняется следующим образом:

Если мы сортируем список и сохраняем новый список в переменную то

будет ошибкой. Правильнее будет сначала выполнить сортировку, а уже сортированный список сохранить в переменную

Словари

Что такое словарь?

Словарь это неупорядоченный список. Вместо индексации здесь у всех данных есть свой ключ — буквенный.

Как создать словарь?

Словари в Python объявляются таким путём:

Как работать с определённым элементом словаря?

Вывести определённый элемент из словаря на экран можно вот так:

Сейчас мы вывели значение элемента в словаре с ключем ‘key1’.

Точно также — работа с определённым элементом из словаря идентична работе с переменной, всё разбирать мы не будем.

Как работать с самим словарем?

Таблица методов для работы со словарями

my_dict.clear()

my_dict.copy()

Возращает копию словаря

my_dict.get(key[, default])

Возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None)

my_dict.items()

Возвращает пары (ключ, значение)

my_dict.keys()

my_dict.pop(key[, default])

Удаляет ключ и возвращает значение. Если ключа нет, возвращает default (по умолчанию бросает исключение).

my_dict.popitem()

Удаляет пару (ключ, значение). Если словарь пуст, бросает исключение KeyError. Помните, что словари неупорядочены

my_dict.values()

Возвращает значения из словаря

Подведём итоги

Для цен в магазине лучше использовать словари, можно указать для чего конкретно цена, для списка банковских клиентов — списки, можно рассортировать по алфавиту. А дальше — по аналогии.

Python Dictionaries: A Comprehensive Tutorial (with 52 Code Examples)

A Python dictionary is a data structure that allows us to easily write very efficient code. In many other languages, this data structure is called a hash table because its keys are hashable. We’ll understand in a bit what this means.

A Python dictionary is a collection of key:value pairs. You can think about them as words and their meaning in an ordinary dictionary. Values are said to be mapped to keys. For example, in a physical dictionary, the definition science that searches for patterns in complex data using computer methods is mapped to the key Data Science.

In this Python tutorial, you’ll learn how to create a Python dictionary, how to use its methods, and dictionary comprehension, as well as which is better: a dictionary or a list. To get the most out of this tutorial, you should be already familiar with Python lists, for loops, conditional statements, and reading datasets with the reader() method. If you aren’t, you can learn more at Dataquest.

What Are Python Dictionaries Used for?

Python dictionaries allow us to associate a value to a unique key, and then to quickly access this value. It’s a good idea to use them whenever we want to find (lookup for) a certain Python object. We can also use lists for this scope, but they are much slower than dictionaries.

This speed is due to the fact that dictionary keys are hashable. Every immutable object in Python is hashable, so we can pass it to the hash() function, which will return the hash value of this object. These values are then used to lookup for a value associated with its unique key. See the example of the use of the hash() function below:

The string b has a hash value of 2132352943288137677 . This value may be different in your case.

How to Create a Dictionary?

But let’s stop with the theory and go straight to the dictionary creation. We have two main methods to define a dictionary: with curly braces <> or using the dict() method. We’ll create two empty dictionaries:

We can see that both dictionaries have the same data type and are equivalent. Now let’s populate a dictionary with keys and values. We can do it by using squared brackets, like this dictionary[key] = value . We can then access the value by using bracket notation with the key we want the value of between the brackets: dictionary[key] .

The value of key1 is returned. We can also create a prepopulated dictionary using the syntax below:

Ultimately, another method is using dict() , in which we supply keys and values as a keyword argument list or as a list of tuples:

We used the string data type for the key and the value, but what are the other admissible data types? In Python dictionaries, keys should be hashable objects (even if it’s not technically correct, we can also say that the objects should be immutable). Thus, mutable data types like lists, aren’t allowed. Let’s try to hash() different data types and see what happens:

Integers, floats, strings, and tuples are hashable data types (and they are also immutable) while lists are an unhashable data type (and they are mutable). Python uses hash values to quickly access a dictionary’s values.

On the other hand, values can be of whatever type. Let’s add more elements to the dictionary using different data types:

Additionally, we can modify the value of a key with bracket notation that we used to populate a dictionary:

Finally, dictionary keys should be unique. Let’s try to create a dictionary with duplicate keys:

Only the value of the last key is returned, so we can technically use duplicate keys, but it’s not recommended because one of the strengths of dictionaries is to quickly retrieve a value associated with some key. If there are duplicates, we may return a value we didn’t want. Imagine that we look up for the meaning of the word "data" and find 10 different entries for this word in a dictionary; it may be confusing.

Python Dictionary Methods

Now let’s see what methods we can use to work with dictionaries.

update()

The update() method is useful whenever we want to merge dictionaries or add new key:value pairs using an iterable (iterables are, for instance, lists or tuples). Let’s make an example using characters from the Harry Potter universe and the houses they belong to (spoiler: we’ll use Harry Potter datasets later on!):

Let’s now add other characters and their houses using different options we have available for the update() method:

We can see that the dictionary now contains Albus Dumbledore and Luna Lovegood. We can also use an iterable to add new elements to the dictionary:

We used a list of lists where the first element of each list is the character name and the second element is their house. The update() method then will automatically associate the first element (key) with the second element (value). For the sake of the experiment, try to update the dictionary with a list of lists but with three elements in each nested list.

We can also use a list of tuples:

What if we want to delete a key:value pair from a dictionary? We can use the del statement. It’s essential to say that del isn’t an exclusive dictionary method but rather a Python keyword that we can use in multiple situations to delete whatever Python object (like variable, function, class, list’s element, etc.).

If we’re trying to delete a pair that isn’t present in the dictionary, we’ll get a KeyError :

popitem() and pop()

Sometimes, we need to delete the last item that was inserted in a dictionary. The popitem() method is the way! Note that before Python 3.7, this method removes a random element from a dictionary:

We can also remove a specific key:value pair and return the value using the pop() method:

If we try to access a value of the key that doesn’t exist in the dictionary, Python will return a KeyError . To get around this problem, we can use the get() method that will return the value if its key is in the dictionary, or it will return some default value that we set:

setdefault()

The setdefault() method is often confused with the get() method. They perform more or less the same task. Indeed, if we suspect that there is a non-existing key in the dictionary, we can use this method to return a default value. However, in contrast to get() , this method inserts the default value of this key in the dictionary:

items() , keys() , and values()

What if we want to return all the key:value pairs? Or just the keys? What about the values?

The answer to the first question is the items() method. When used on a dictionary, it will return a dict_items object, which is essentially a list of tuples, each containing a key and a value. This method may be useful when we loop through a dictionary as we’ll see later.

If we want to get just the keys, we should use the keys() method. It will return a dict_keys object:

Finally, we have the values() method that will return the values as a dict_values object:

When Do I Use All These Methods?

After this overview, you may feel overwhelmed by the amount of information. It’s also not easy to determine when you should use the Python dictionary methods. No worries — that’s absolutely okay. You shouldn’t try to remember every single method and its use cases. When you have a real-world problem in front of you (Dataquest guided projects can be a good start), and you have to use dictionaries, just head back to this Python tutorial and see if you can solve your problems with one of these methods. This is the only way you can gain valuable experience and become much faster at using dictionary methods in your future projects!

Looping Through a Dictionary

As we’re able to loop through lists, we’re also able to loop through dictionaries. They hold two different types of elements, keys and values, so we can either loop through both types of elements simultaneously or just one of them.

First of all, we’ll use the items() method, which yields both keys and values:

We can see that this method allows us to access both keys and values. What if we’re only interested in keys? Or only in values?

Let’s get more practical and also learn a slightly more advanced method. Sometimes, we need to compute the frequency of each value in a dictionary. We can use the Counter() method from collections , which is a great Python module with plenty of useful containers that make our coding lives easier.

The returned object Counter is actually very similar to a dictionary. We can use the keys() , values() , and items() methods on it!

Frequency Tables

Python dictionaries are immensely handy when we have to create so-called frequency tables. Simply put, keys are the objects for which we want to count the frequency, and the values are the frequencies. As an example, we’ll be using the Harry Potter Movies Dataset from Kaggle (the Character.csv dataset). Let’s say that we want to count the frequency of each house present in the dataset. To do so, we first have to create an empty dictionary that will contain the frequency table. Then, we have to loop through the list of houses, and if the key for a house is already present in the frequency table, we add 1 to its value. Otherwise, we create a key for the current house and map it to value 1 (it’s one because we encounter this element for the first time). We also have to account for missing data in our dataset.

Most of the characters from the dataset are from Gryffindor. To practice, try to create frequency tables of the other columns.

Nested Dictionaries

Similar to lists, there are also nested dictionaries. In other words, a dictionary can contain another dictionary! Let’s use the Movies.csv dataset from the same set of Harry Potter datasets. It may happen that in your career, you work with multiple datasets at the same time. One way to organize them is by using dictionaries:

Now we can easily access each dataset or a specific entry. To illustrate this, let’s access the columns of the characters dataset:

We can also access the columns of both datasets with a for loop:

An alternative to this approach (especially when we don’t have dozens of datasets) is to reorganize each dataset in a dictionary. It will simplify our work when we have to access different entries:

Dictionary Comprehension

Dictionary comprehension in Python is an elegant and efficient method to create new dictionaries. You have probably already learned something about list comprehension. Just a quick reminder: comprehension in Python means applying the same operation on each element of an iterable (like a list). Let’s illustrate how this technique works. For example, we want a dictionary that holds the runtimes of each of the Harry Potter movies. Let’s create it from the dataset’s dictionary movies_dict :

Now we want to convert each runtime from minutes to hours. First of all, we can do it with a regular for loop:

However, we can simplify the above code by creating the runtime dictionary in just one line:

Let’s dissect the code above. First, look at where the for loop is now: we’re still looping through the items of the runtimes dictionary. Now notice the curly braces: we’re writing the code inside a dictionary! k is the current key of our for loop, and after the colon ( : ) we perform the operation of rounding and division by 60 directly on v , which is the value of the for loop.

This code performs exactly the same operations as before, but it does it in 1 line instead of 3 lines.

Moreover, we can also add conditional statements. Let’s say that we want to exclude the movies that are shorter than 2.5 hours:

We just add an if-statement, and that’s it.

Dictionary comprehension also works with the keys in a similar manner. Try it yourself!

Note that if we have multiple conditional statements or complicated operations, it’s better to use a regular for loop because dictionary comprehension may become an incomprehensible coding jungle, which undermines the benefits of Python readability.

Python Dictionary vs List: Which Is Better?

Now that we know more about Python dictionaries, it’s time to compare dictionaries and lists. Which is better? Neither better than the other, but they are helpful in different coding tasks.

The rules to choose one of these data structures are actually pretty simple:

  1. When you just need a sequence of elements that you can access with indexing, choose a list.
  2. If you need to quickly access an element mapped to a specific unique key, choose a dictionary.

There is a bit more than that. Dictionaries are much faster if we want to access a specific element because they have a constant runtime, which means that the runtime doesn’t depend on the size of the input object. In contrast, when we want to see if an element exists in a list, the runtime will depend on the size of this list (Python loops through the entire list). Look at the examples:

It may seem that the difference is negligible, but as we increase the input size the difference will skyrocket.

Let’s make a more concrete example. Often, we’ll want to access a certain element in either a list or a dictionary. To find this element in a list, we first have to loop through the entire list, while in a dictionary, we can quickly access the same element by using its unique key. Let’s find 9000000 in the list and the dictionary defined above.

It took the dictionary almost no time to locate the number, while the list took around 1 second to perform the same operation. The dictionary is almost one million times faster!

Bonus: Using defaultdict() to Handle Missing Keys

Recall that we used the setdefault() method to insert a default key and its value in a dictionary. We also used the get() method to return a default value of a non-existing key. A more Pythonic way to perform similar operations is by using defaultdict() from the collections module(). We can initialize a dictionary with a default value data type by calling it and passing the data type we want to the method. Now if we try to access a missing key, the dictionary will create this key and map a default value to it:

Here the method created a key missing_key and assigned an empty list to it because that’s the default value of our dictionary. We can now append some values to this list:

The arguments we pass to defaultdict() must be callable. If we pass a non-callable object to defaultdict() we’ll get a TypeError :

In contrast, we can pass whatever object to the setdefault() method:

Let’s also look at the get() method. We use it when we want to return a value of a key we suspect doesn’t exist. This method will return only the value but won’t change the dictionary in any way:

Now we should be able to understand the difference between these three methods.

Conclusion

Here’s what we’ve covered in this tutorial:

  • Dictionaries in Python
  • How dictionaries allow us to quickly access a certain Python object
  • Creating a dictionary with the dict() method or curly braces
  • Python dictionary methods
  • Looping through a dictionary
  • Creating frequency tables
  • Nested dictionaries
  • Dictionary comprehension
  • When to use a list or a dictionary
  • Using defaultdict() to handle missing keys

Feel free to connect with me on LinkedIn or GitHub. Happy coding!

About the author

Artur Sannikov

I am a Molecular Biology student at the University of Padua, Italy interested in bioinformatics and data analysis.

Словари в Python

В этом руководстве вы узнаете всё о словарях в Python: как их создавать, как добавлять, удалять, как получать из них элементы, а еще познакомитесь со встроенными методами словарей.

Словарь — это неупорядоченный набор элементов. Элемент словаря представляет собой пару ключ: значение . Словари оптимизированы для получения значений по заданному ключу.

Как создать словарь

Чтобы создать словарь в Python, необходимо прописать элементы внутри фигурных скобок <> и разделить их запятыми.

В элементе содержится ключ и соответствующее значение, они записываются так: (ключ: значение) .

В словарях значения могут повторяться и быть любого типа. Ключи же повторяться не могут и должны быть неизменяемым типом (строками, числовыми типами и кортежами с неизменяемыми элементами).

Как вы увидели выше, мы можем создать словарь с помощью встроенной функции dict() .

Как получить элементы из словаря

В отличие от других типов данных, где для доступа к элементам используется индексация, в словаре используются ключи. Они используются внутри квадратных скобок или в качестве аргумента метода get() .

При использовании квадратных скобок и отсутствии элемента в словаре вызывается ошибка KeyError. При использовании метода get() и отсутствии элемента возвращается None .

Вывод:

Как изменить или добавить элементы в словаре

Словари — изменяемый тип данных. Это значит, что в него можно добавить новые элементы или изменить уже существующие с помощью оператора присваивания.

Если добавляемый ключ есть в словаре, значение элемента изменяется. Если же такого ключа еще нет, то в словарь добавляется новая пара (ключ: значение) .

Вывод:

Как удалить элементы из словаря

Удалить нужный элемент словаря по ключу можно с помощью метода pop() . Этот метод удаляет элемент с соответствующим ключом и возвращает значение.

Удалить произвольную пару (ключ, значение) можно с помощью метода popitem() . Очистить весь словарь за один раз можно с помощью метода clear() .

Также можно использовать ключевое слово del для удаления отдельных элементов или же всего словаря.

Вывод:

Методы словарей

В таблице ниже указаны доступные методы словарей. Некоторые из них мы уже использовали в примерах выше.

Метод

Что делает

Удаляет все элементы из словаря

Возвращает неглубокую копию словаря

Возвращает словарь с ключами из seq и значениями, равными v (по умолчанию None )

Возвращает значение ключа key . Если key не существует, возвращает d (по умолчанию None )

Возвращает новый объект элементов словаря в формате (ключ, значение)

Возвращает новый объект с ключами словаря

Удаляет элемент с ключом key и возвращает его значение или d , если key не найден. Если d не было обозначено и key не найден, вызывает ошибку KeyError.

Удаляет и возвращает произвольную пару (ключ, значение) . Вызывае ошибку KeyError, если словарь пустой.

Если ключ key есть в словаре, возвращает соответствующее ему значение. Если нет, добавляет в словарь элемент с ключом key и значением d и возвращает d (по умолчанию None )

Обновляет словарь имеющимися парами ключ/значение из other , перезаписывая существующие ключи

Возвращает новый объект со значениями словаря

Вывод:

Представление словарей

Представление словарей — элегантный и лаконичный способ создать новый словарь из итерируемого объекта.

Представление словарей состоит из выражения ключ: значение , за которым следует for , и всё это — внутри фигурных скобок <> .

Создадим словарь с парами чисел и их квадратов в качестве элементов:

Вывод:

То же самое можно сделать иначе, но так будет длинее:

Вывод:

В представлении словарей выражений for и if опционально может быть больше.

Необязательное выражение if поможет отфильтровать элементы для создания нового словаря.

Давайте создадим словарь только с квадратами только нечетных чисел:

Вывод:

Другие операции со словарями

Проверка на вхождение в словарь

Проверить, есть ли ключ в словаре, можно с помощью ключевого слова in . Отметим, что проверку на вхождение можно провести только над ключами, не над значениями

Вывод:

Итерирование по словарю

Мы можем пройтись по всем ключам словаря, используя цикл for .

Вывод:

Встроенные функции для словарей

Встроенные функции all() , any() , len() , cmp() , sorted() и т. д. часто используются со словарями для разных задач.

Функция

Описание

Возвращает True , если все ключи словаря = True (или если словарь пуст)

Возвращает True , если хотя бы один ключ словаря = True . Если словарь пуст, возвращает False .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *