Python Dictionaries
![]()
Data structures are basically containers that store data in predefined layouts, optimized for certain operations — like apples in a box, ready for picking.
The Python programming language natively implements a number of data structures. Lists, tuples, sets, dictionaries are but some of them. We will be looking at the dictionary data type in subsequent sections.
What are dictionaries ?
A dictionary in python is a mapping object that maps keys to values, where the keys are unique within a collection and the values can hold any arbitrary value. In addition to being unique, keys are also required to be hashable.
An object is said to be hashable if it has a hash value (implemented by a __hash__() method) that does not change during the object’s lifetime. Most commonly, we use immutable data types such as strings, integers, and tuples (only if they contain similarly immutable types) as dictionary keys.
A dictionary’s data is always enclosed by a pair of curly braces < >, and would normally look like this:
We have created a dictionary named my_dict where each key-value pair is separated by a full colon, with the key-value pairs as:
- first_name — John
- last_name — Snow
- age — 16
- gender — Male
Typically dictionaries store associative data, i.e data that is related. Examples of such data include the attributes of an object, SQL query results and csv-formatted information. Throughout this article, we will be using dictionaries to store job listing details from Kaggle.
Comparisons
Dictionaries are an implementation of Associative Arrays. All Associative arrays have a structure of (key, value) pairs, where each key is unique for every collection. Other languages also have similar implementations, such as:
- Maps in Go
- std::map in C++
- Maps in Java
- JavaScript objects
Unlike sequenced data types like lists and tuples, where indexing is achieved using positional indices, dictionaries are indexed using their keys. Therefore, individual values can be accessed using these keys.
Dictionary Operations
1. Creation
- We initialize an empty dictionary using a pair of curly braces. This approach is often used when we expect to store some data at later stages of our operation.
In the line above, we have created an empty dictionary named empty_dict .
- For instances when we have our data beforehand, we use curly braces with the key-value pairs. We can now create a dictionary to represent the second row of data in the jobs.csv file.
We just created a dictionary with the keys title , location , job_type , employer , category and assigned it to the variable job1 .
- Dictionaries can also be created using the dict() constructor. To do this we pass the constructor a sequence of key-value pairs. We could also pass in named arguments.
Let's create a dictionary to represent the third row of data in the jobs.csv file, using both of these methods.
We passed a sequence, in this case a list of key-value tuples, to the dict() constructor to create our dictionary, and assigned it to the variable job2 .
Here, we created a dictionary using named arguments. The keys are the argument names, while the values are the argument values. It is however important to note that this method is only suitable when our keys are just simple strings.
2. Accessing Items
As we mentioned earlier on, dictionaries are indexed using their keys.
To access a particular value in a dictionary we use the indexing operator (key inside square brackets). However, to use this method, we need to make sure the key we intend to retrieve exists, lest we get a KeyError . Checking for availability of a key is as easy as using the in operator.
- In the example above we use indexing to access the title from job2 after making sure it is available using in .
- If you are like me, this is probably a lot of work. The good news, however, is that we have a better tool — the get() method. This method works by giving out a value if the key exists, or returning None . None sounds better than an error, right?
What if we want to go even further, and return something, a placeholder of sorts? get() takes a second argument, a default value to be used in place of None . Now let's use in to check if title exists in job2 , then we can use indexing to retrieve its value. We'll also go ahead and use get() to retrieve salary from job2 .
Here, we use get() to access the title and salary .
However, job2 doesn't have a salary key so the return value is None . Adding a second argument, to get() now gives us 5000 instead of None .
3. Modification
Dictionaries can be modified directly using the keys or using the update() method. update() takes in a dictionary with the key-value pairs to be modified or added. For our demonstration, let's:
- Add a new item (salary) to job2 with a value of 10000.
- Modify the job_type to be "Part time".
- Update the salary to 20000.
- Update the dictionary to include a new item (available) with a value of True .
To add a new entry, we use syntax similar to indexing. If the key exists, then the value will be modified, however, if the key doesn’t exist, a new entry will be created with the specified key and value.
- Initially, we assigned a value of 10000 to the salary key, but since salary doesn't exist, a new entry is created, with that value. For our second example, the job_type key exists, the value is modified to "Part time".
- Next, we use the update() method to change the salary value to 20000, since salary is already a key in the dictionary. Finally, we apply update() to the dictionary, a new entry is created with a key of available and value of True .
A particularly nice use case for update() is when we need to merge two dictionaries. Say we have another dictionary extra_info containing extra fields for a job, and we would like to merge this with job2 .
4. Deletion
We can now remove the just created salary entry from job2 , and remove everything from job1 .
To remove the entries associated with the salary and available keys from job2 , we use the del keyword. Now if we go ahead and print job2 , the salary and available entries are gone.
Removing all items from job1 entails using the clear() method, which leaves us with an empty dictionary. If we don't need a dictionary anymore, say job1 , we use the del keyword to delete it. Now if we try printing job1 we'll get a NameError since job1 is no longer defined.
6. Iteration
A dictionary by itself is an iterable of its keys. Moreover, we can iterate through dictionaries in 3 different ways:
- dict.values() — this returns an iterable of the dictionary's values.
- dict.keys() — this returns an iterable of the dictionary's keys.
- dict.items() — this returns an iterable of the dictionary's (key,value) pairs.
But why would we need to iterate over a dictionary?
Our dataset has about 860 listings, suppose we wanted to display the properties of all these on our website, it wouldn’t make sense to write the same markup 860 times. It would be efficient to dynamically render the data using a loop.
Let’s iterate over job2 using a for-loop using all the three methods. Furthermore we'll use the csv module to read our csv-formatted data in to a list of dictionaries, then we'll iterate through all the dictionaries and print out the keys and values.
- First, we loop through the dictionary as it is. This is similar in output to stepping through the job2.keys() iterable.
- Secondly, we iterate through job2.values() while printing out the value.
- Finally, we step through the list of dictionaries, and for each one, loop through the keys and values simultaneously.
We include both key and value in the for-loop constructor since job.items() yields a tuple of key and value during each iteration. We can now apply any kind of operation to our data at this point. Our implementation simply prints out the pair at each step.
7. Sorting
Borrowing from our description of dictionaries earlier, this data type is meant to be unordered, and doesn’t come with the sorting functionality baked in. Calling the sorted() function and passing it a dictionary only returns a list of the keys in a sorted order, since the dictionary is an iterable of its keys.
If we use the items() iterable we could sort the items of our dictionary as we please. However, this doesn't give us our original dictionary, but a list of key-value tuples in a sorted order.
Say we wanted to display the job details in the above example in alphabetical order, We would need to alter our iteration to give sorted results. Lets walk through the example again an see how we would achieve that functionality.
- In this example we use python’s inbuilt sorted() function which takes in an iterable (our dictionary's items).
- The key argument of the sorted() function instructs sorted() to use the value at index 0 for sorting. This named argument points to a lambda function which takes in an item, say (“a”, “b”) and returns the value at the item’s first index, in this case “a”.
Similarly, to sort by the values, we use index 1 instead of index 0.
Other Methods
Dictionaries have other methods that could be used on demand. To read up further on these, please consult the python documentation. Here are some other useful methods:
- pop(key,default) — deletes the key key and returns it, or returns an optional default when the key doesn't exist.
- copy() — returns a shallow copy of the original. This shallow copy has similar references to the original, and not copies of the original's items.
- setdefault(key,default) — returns the value of key if in the dictionary, or sets the new key with an optional default as its value then returns the value.
Speeding Up your Code
Dictionary unpacking can greatly speed up our code. It involves destructuring a dictionary into individual keyword arguments with values.
This is especially useful for cases that involve supplying multiple keyword arguments, for example in function calls.
To implement this functionality we use the iterable unpacking operator ( ** ).
What if we needed Job objects to work with, instead of dictionaries? We shouldn't have to do some heavy lifting to get our data reorganized in to objects.
Let's see how we could translate our dictionaries into objects, by again tweaking our previous code.
- To instantiate a new Job object, traditionally, we would need to pass in all the required arguments. However, with unpacking, we just pass in a dictionary with the ** operator before it.
The operator unpacks the dictionary in to an arbitrary number of named arguments. This approach is much cleaner and involves less code.
8. Anti-patterns: Wrong usage
Compared to lists and tuples, dictionaries take up more space in memory, since they need to store both the key and value, as opposed to just values.
- Therefore, dictionaries should only be used in cases where we have associative data, that would lose meaning if stored in lists, or any other sequenced data type.
- Dictionaries are mutable, hence not suitable for storing data than shouldn’t be modified in place.
- Since dictionaries are unordered, it would not be sensible to store strictly arranged data in them.
A possible candidate data type for this scenario would be the OrderedDict from the collections module. An OrderedDict is a subclass of the regular dict class, with the advantage of tracking the order in which keys were added. - Dictionaries are well-designed to let us find a value instantly without necessarily having to search through the entire collection, hence we should not use loops for such an operation.
We have a variable key_i_need containing the key we want to search for. We have used a for loop to traverse the collection, comparing the key at each step with our variable. If we get a match, we assign that key's value to the variable target .
This is the wrong approach. We should instead use get() , and pass it the desired key.
Performance Trade-offs
Dictionary operations are heavily optimized in python, especially since they’re also extensively used within the language.
For instance, members of a class are internally stored in dictionaries.
Most dictionary operations have a time complexity of O(1) — implying that the operations run in constant time relative to the size of the dictionary. This simply means that the operation only runs once irregardless of the dictionary size.
Creating a dictionary runs in a linear time of O(N), where “N” is the number of key-value pairs.
Similarly, all iterations run in O(N) since the loop has to run N times.
Conclusion
Dictionaries come in very handy for regular python usage. They are suitable for use with unordered data that relies on relations. Caution should however be exercised to ensure we do not use dictionaries in the wrong way and end up slowing down execution of our code. For further reading please refer to the official python documentation on mapping types.
5. Data Structures¶
This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.
5.1. More on Lists¶
The list data type has some more methods. Here are all of the methods of list objects:
Add an item to the end of the list. Equivalent to a[len(a):] = [x] .
list. extend ( iterable )
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
Remove all items from the list. Equivalent to del a[:] .
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Return the number of times x appears in the list.
list. sort ( * , key = None , reverse = False )
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Reverse the elements of the list in place.
Return a shallow copy of the list. Equivalent to a[:] .
An example that uses most of the list methods:
You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . 1 This is a design principle for all mutable data structures in Python.
Another thing you might notice is that not all data can be sorted or compared. For instance, [None, ‘hello’, 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.
5.1.1. Using Lists as Stacks¶
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
5.1.2. Using Lists as Queues¶
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
5.1.3. List Comprehensions¶
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:
which is more concise and readable.
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:
and it’s equivalent to:
Note how the order of the for and if statements is the same in both these snippets.
If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.
List comprehensions can contain complex expressions and nested functions:
5.1.4. Nested List Comprehensions¶
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
Consider the following example of a 3×4 matrix implemented as a list of 3 lists of length 4:
The following list comprehension will transpose rows and columns:
As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:
which, in turn, is the same as:
In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:
See Unpacking Argument Lists for details on the asterisk in this line.
5.2. The del statement¶
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:
del can also be used to delete entire variables:
Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.
5.3. Tuples and Sequences¶
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
The statement t = 12345, 54321, ‘hello!’ is an example of tuple packing: the values 12345 , 54321 and ‘hello!’ are packed together in a tuple. The reverse operation is also possible:
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
5.4. Sets¶
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not <> ; the latter creates an empty dictionary, a data structure that we discuss in the next section.
Here is a brief demonstration:
Similarly to list comprehensions , set comprehensions are also supported:
5.5. Dictionaries¶
Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .
It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: <> . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.
Here is a small example using a dictionary:
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
5.6. Looping Techniques¶
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.
It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.
5.7. More on Conditions¶
The conditions used in while and if statements can contain any operators, not just comparisons.
The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.
Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .
Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.
The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,
Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
5.8. Comparing Sequences and Other Types¶
Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:
Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.
Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort(); .
Dictionaries and Sets
It is also known in Python as a “mapping”, as it “maps” keys to values.
It is like an array, in that it holds a number of items, and you can index into it to get at particular items. But it can use arbitrary indexes, rather than a sequence of numbers.
These indexes are called “keys”, and the items stored are called “values”.
So for any Python sequence, you might do:
for a dict, you do:
It is very common to use strings as keys in a dictionary. So common that virtually all examples you’ll see both here and on the Internet use strings as keys. And many other languages have similar objects that only allow strings (like JavaScript objects, for instance). Python dicts, on the other hand, can use many types as keys, and this can be a very powerful feature to keep in mind.
Dictionary Constructors
So how does one make a dict? There are a few ways…
The dict “literal”:
Calling the dict type object constructor:
Dictionary Indexing
And how do you get stuff out (index it)?
The same way you index a sequence, except the index (now called a key) can be various types, rather than just an integer:
What if the key doesn’t exist in the dict? You get a KeyError exception:
What can keys be?
Surely not ANYTHING?
Not quite: keys can be any “immutable”:
-
number
-
string
-
tuple
What if you try to use a mutable type?
Actually – any “hashable” type.
So, technically, it’s not mutability, but hashability that matters.
Although for most intents and purposes, you want to use immutable types as keys in dicts.
Hashing
Hash functions convert arbitrarily large data to a small proxy (usually an integer).
They always return the same proxy for the same input.
MD5, SHA, etc, are some well known hash algorithms.
Dictionaries hash the key to an integer proxy and use it to find the key and value.
Key lookup is efficient because the hash function leads directly to a bucket with very few keys (often just one).
What would happen if the proxy (hash) changed after storing a key?
(Answer: you wouldn’t be able to find it again!)
Hashability requires immutability.
Key lookup is very efficient:
The access time is constant regardless of the size of the dict.
Dictionary indexing
Note: cPython name look-ups are implemented with dicts – it’s highly optimized.
-
lookup is one way.
-
requires visiting the whole dict.
If you need to check dict values often, create another dict or set.
(But note that it’s then up to you to keep them in sync).
Dictionary Ordering (not)
Traditionally, dictionaries have had no defined order. See this example from Python 3.5:
Note how I defined the dict in a natural order, but when it gets printed, or you display the keys, they are in a different order.
However, In cPython 3.6, the internal implementation was changed, and it does happen to preserve order. In cPython 3.6, that is considered an implementation detail – and you should not count on it! However, as of cPython 3.7, dictionaries preserving order are part of the language specification. This was declared by Guido on the python-dev mailing list on Dec 15, 2017 <https://mail.python.org/pipermail/python-dev/2017-December/151283.html>.
When new items are added to a dict, they go on the “end”:
and dict.popitem() will remove the “last” item in the dict.
CAUTION This is new behavior in cPython 3.6 – older versions of Python (notably including Python 2) do not preserve order. In older versions, there is a special version of a dict in the collections module: collections.OrderedDict which preserves order in all versions of Python, and has a couple extra features.
Also: while Python dicts now preserve order, they are not really a fully ordered object: there is no direct way to get, say, the “third” item in a dict, or to inset an item at a particular location.
Словари в Python: что нужно знать и как пользоваться
Продолжаем осваивать «змеиный» язык. Сегодня поговорим о словарях — важном инструменте для хранения данных в Python.


Иллюстрация: Оля Ежак для Skillbox Media

Нет, словари нужны не для того, чтобы переводить запутанный код программистов на человеческий. Их используют для того, чтобы удобно хранить данные и быстро получать к ним доступ по запросу. В этой статье подробно разберём, что такое словари и как с ними работать в Python.
А если вы уже знакомы со словарями и хотите освежить в памяти отдельные моменты, используйте навигацию или скачайте шпаргалку в конце статьи.
Что такое словарь
Словарь в языках программирования — это что-то вроде телефонной книги, где под каждым номером скрывается какой-то человек.
Только на языке разработчиков номера называют ключами, а людей, которым они принадлежат, — значениями. Вот как это можно представить в виде таблицы:
| Ключ | Значение |
|---|---|
| 8 (984) 123-53-11 | Дизайнер Валера |
| 8 (934) 256-32-54 | Менеджер Егор (не отвечать) |
При этом ключи в словарях уникальны, а значения могут повторяться. Условно говоря, дизайнеру Валере может принадлежать сколько угодно номеров — но у каждого номера может быть только один владелец.
Мы привели пример с телефонной книгой, но вы можете хранить в словаре всё что угодно: названия песен, имена покупателей, товары в интернет-магазине и так далее. При этом стоит помнить важное правило:
Ключами могут быть строки, числа (целые и дробные) и кортежи. Нельзя использовать списки, словари и другие изменяемые типы данных. В значения можно «положить» любые типы данных — и даже новые словари.
Например, давайте в качестве ключа укажем название книги, а значением сделаем её автора.
| Ключ | Значение |
|---|---|
| «Гарри Поттер и философский камень» | Джоан Роулинг |
| «Убить пересмешника» | Харпер Ли |
| «Грокаем алгоритмы» | Адитья Бхаргава |
Теперь, если у нас есть название книги, мы можем быстро найти её автора. Этим словари и удобны: знаем ключ — моментально получаем значение.
Словарь — это неупорядоченная структура данных. Это значит, что все пары «ключ — значение» хранятся в произвольном порядке. Идея в том, что нам неважно, где находится элемент: в начале, в серединие или в конце. Важно то, что он лежит где-то внутри и мы можем при случае его достать.
Пример упорядоченной структуры — это список. Там у всех элементов есть свои индексы, благодаря которым их можно отсортировать как душе угодно. Если хотите больше знать о списках, читайте другую нашу статью. А мы пойдём дальше — создадим наш первый словарь.
Как создать словарь в Python
Словари в Python оформляются фигурными скобками. Внутри них находятся пары «ключ — значение». Первым пишется ключ, а затем, через двоеточие, — значение. Сами пары отделяются друг от друга запятыми.
По идее, можно вообще не указывать для ключей никаких значений: язык автоматически подставит вместо них значения None. Но словарь при этом всё равно будет работать.
Выведем на экран содержимое словаря с помощью функции print:
Показались только ключи. Теперь попробуем вывести полноценный словарь со значениями:
Операции со словарями
Мало просто создать словарь — иногда нам нужно взаимодействовать с отдельными его элементами. Разберёмся с базовыми операциями.
Как достать значение ключа из словаря
Если нам известен ключ, можно быстро извлечь из словаря его значение — для этого используйте квадратные скобки.
Если указать неправильный ключ, мы получим ошибку:
Ошибка говорит нам, что по заданному ключу ничего не нашлось.
Как добавить новый элемент в словарь Python
Теперь попробуем добавить в наш словарь с книгами ещё одну запись. Чтобы это сделать, в квадратных скобках указываем ключ, а потом, через знак равенства, добавляем значение.
Пробуем вывести содержимое словаря на экран — видим, что новая запись добавилась в самом конце.
Как удалить элемент из словаря Python
Чтобы удалить элемент из словаря, используют команду del. При этом нам достаточно ввести только ключ, а значение удалится вместе с ним.
Синтаксис немного необычный: мы пишем команду del перед тем, как обратиться к словарю. Но всё прекрасно работает, мы проверили 🙂
Как изменить значение ключа в словаре
Здесь всё просто: в квадратных скобках пишем уже существующий ключ, а через знак равенства указываем новое значение.
Выводим в консоль — видим, что значение первой пары поменялось.
Важное замечание. Если указать неправильный ключ, то мы вместо обращения к уже существующей паре создадим новую:
Чтобы избежать таких ситуаций, можно использовать безопасный метод get(), о котором мы поговорим в следующем разделе.
Какие методы работают со словарями в Python
Для словарей создали много полезных методов, которые облегчают привычные операции — например, можно одной функцией добавить в словарь несколько элементов или предусмотреть обработку ошибок.
Метод update()
Что делает: добавляет в словарь одну или сразу несколько пар «ключ — значение».
Как использовать: объявляем метод update(), внутри которого создаём новый словарь из элементов, которыми хотим дополнить существующий.
Метод get()
Что делает: возвращает значение из словаря по ключу — или None, если такого ключа не существует.
Попробуем передать ключ, которого нет в словаре:
У этого метода есть тайный козырь в рукаве. Вместо сухого и формального None он может вывести любое значение, которое вы захотите, — например, сообщение об ошибке. Для этого надо прописать нужное значение вторым аргументом. Мы решили добавить строчку с ошибкой:
В этом состоит главное преимущество метода get() перед обычными квадратными скобками — для обработки ошибок можно не писать объёмные конструкции try/except, а ограничиться всего одной аккуратной строчкой.
Метод pop()
Что делает: удаляет элемент из словаря по ключу.
Метод keys()
Что делает: возвращает все ключи из словаря — но без значений.
Метод values()
Что делает: возвращает все значения из словаря — но без ключей.