Python Dictionaries

by Alex
Python Dictionaries

In the Python programming language, a dictionary is an unordered collection of arbitrary data, accessible via a key. The elements of such a collection are pairs of objects, each containing a key and a value. Functions are available for working with dictionaries, which change their contents and perform various operations on them. It can be converted to other data types, such as strings.

Creating

Before you start working with the dictionary you should create it. You can do this with the basic tools of the language by assigning any number of pairs of objects to a free variable. The elements must be placed in curly braces, and between the key and value must be a colon. The following example demonstrates the creation of a dictionary named a, which includes keys as numbers and values as strings.

a = {1: "one", 2: "two", 3: "three"}
print(a)

{1: 'one', 2: 'two', 3: 'three'}

You can print the content of the dictionary using the standard print function, specifying the required data set as its argument. The dict method, which retrieves any number of key and value pairs, is also used to fill the dictionary. In this case, only a string can be a key, as shown in the following code example.

a = dict(one = 1, two = 2, three = 3)
print(a)

{'one': 1, 'two': 2, 'three': 3}

Like last time, the print function displays the contents of the dictionary a. In this case, there are pairs of objects, also represented as numbers and strings.

Adding an item

In Python 3, the contents of the dictionary can be changed at any time as you wish. For example, to add a new object pair to the collection, all you need to do is specify a new key in square brackets, along with its corresponding value.

a = {1: "one", 2: "two", 3: "three"}
a[4] = "four"
print(a)

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

The above code applies the assignment operator, so that the new pair (4 : “four”) is placed at the end of the collection a, which was already created before.

Combining dictionaries

If there is a need to move data from one dictionary to another, you should use the update merge function. Call it on the object, which is supposed to be expanded with new pairs of keys and values. Here is an example of how to add to the dictionary in Python:

a = {1: "one", 2: "two", 3: "three"}
b = {4: "four", 5: "five"}
a.update(b)
print(a)

{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

The result of the print method is the display of the updated contents of the dictionary called a.

After merging, the new elements were automatically written to the end of the collection.

Removing an item

If the dictionary contains redundant information, you can easily get rid of it by using the special operation del. To perform it, specify the name of the collection and the key in square brackets. The following example shows the removal of a pair.

a = {1: "one", 2: "two", 3: "three"}
del a[3]
print(a)

{1: 'one', 2: 'two'}

Since the operation got key 3, it also removed the value of three.

Getting the size

The len function allows you to find the current number of elements in the dictionary at any time by passing the name of the collection as an argument. In the example below print method prints the size of the dictionary a.

a = {1: "one", 2: "two", 3: "three"}
print(len(a))

3

Note that the len function returns the exact number of pairs, but not the number of objects. In this case, there is a dictionary, which contains exactly 3 pairs.

Try the dictionary

You can search the elements of the dictionary in several ways, depending on how you want to get the information about its contents. The enumeration of elements can be carried out in order to get them for further processing:

  • Key-value pair;
  • Search for all keys;
  • Value Pairing.

This example shows how to display all pairs of this collection in key : value format. To do this, use the for loop and the items function that works with dictionary items.

a = {1: "one", 2: "two", 3: "three"}
for key, value in a.items():
    print(key, ":", value)

1 : one
2 : two
3 : three

To get only keys, apply the keys method by calling it on the dictionary.

a = {1: "one", 2: "two", 3: "three"}
for key in a.keys():
    print(key)

1
2
3

The same way should be done to print only the values of the dictionary. However, in this case the values method is used in the for loop.

a = {1: "one", 2: "two", 3: "three"}
for val in a.values():
    print(val)

one
two
three

In both cases only the selected part of the pair, the key or the value, is shown.

Search

You can check if a certain key exists by using the in operation. To do this, just print its result for the dictionary named a.

a = {1: "one", 2: "two", 3: "three"}
print(2 in a)
print(4 in a)

True
False

As you can see, the result of the key 2 check is positive (True). In the second case, False is printed, because key 4 is not found in the dictionary.

Sorting

The language tools allow you to sort the dictionary by keys and values, as needed, in Python. In the following example, there is a collection of data named a that contains information in random order. The keys here are numbers, and the values are strings. Sorting is done by the imported operator module and the built-in itemgetter method, which gets 0 or 1.

import operator
a = {2 : "two", 3 : "three", 1 : "one"}
b = sorted(a.items(), key = operator.itemgetter(0))
print(b)
b = sorted(a.items(), key = operator.itemgetter(1))
print(b)

[(1, 'one'), (2, 'two'), (3, 'three')]
[(1, 'one'), (3, 'three'), (2, 'two')]
As you can see, the argument 0 allows you to sort the dictionary by key, while 1 allows you to output its contents in alphabetical order of values.

Comparison

Sometimes you need to make sure that two dictionaries contain exactly the same data, or to find out which collection is larger or smaller. In this case, you can use cmp method, taking two dictionaries as parameters.

a = {1: "one", 2: "two", 3: "three"}
b = {4: "four", 5: "five"}
c = {1: "one", 2: "two", 3: "three"}
print(cmp(a, b))
print(cmp(b, c))
print(cmp(a, c))

1
-1
0

This code shows the cmp method with three combinations of arguments. As you can see, the function returns 1 if the first is greater than the second, -1 if it is the other way around and 0 if the data are identical.

Copying

The copy method is used to copy the contents of one dictionary into another. This example demonstrates the transfer of keys and values from collection a to b.

a = {1: "one", 2: "two", 3: "three"}
b = a.copy()
print(b)

{1: 'one', 2: 'two', 3: 'three'}

As you can see, the order and contents of all pairs have been preserved in the new set.

Clearing

To get rid of all the dictionary elements, call the clear function for it.

a = {1: "one", 2: "two", 3: "three"}
a.clear()
print(a)

{}

The result is a completely empty data set.

Dictionary generator

As with other data sets, dictionaries can be populated using generators. The following example demonstrates the creation of number pairs of the collection using the Python dictionary generator with the range method, receiving 5 as an argument.

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

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Thus, the output is a dictionary a, which includes exactly 5 pairs. The keys are numbers from 0 to 4, and the values are their mathematical squares.

Convert to string

You can very easily convert a dictionary to a string to make it easier to work with the whole representation of its contents. To do that, you will need the str function. As you can see from the results of the type method, the conversion was successful.

a = {1: "one", 2: "two", 3: "three"}
b = str(a)
print(b)
print(type(b))

{1: 'one', 2: 'two', 3: 'three'}
<class 'str'>

Similarly, converting a Python string into a dictionary is done in reverse. It is important that its textual content fits the structure of the collection in question.

a = '{1: "one", 2: "two", 3: "three"}'
b = eval(a)
print(b)
print(type(b))

{1: 'one', 2: 'two', 3: 'three'}
<class 'dict'>

As you can see from the example, the method eval converts all the text of the string into a new dictionary.

Nested

In Python, dictionaries can be nested, that is, they can be part of another larger dictionary. Using the previously familiar curly braces and colons, you can denote the boundaries of this dataset and tell the program key pairs with values.

a = {
    "First": {
        1: "one",
        2: "two",
        3: "three"
    },
    { "second": {
        4: "four",
        5: "five"
    }
}
print(a)

{'First': {1: 'one', 2: 'two', 3: 'three'}, 'Second': {4: 'four', 5: 'five'}}

In the example above, a dictionary a is created, which includes two other dictionaries (First and Second). Those, in turn, contain several key and value pairs.

Summary

The following table shows a brief summary of all the reviewed methods for working with dictionaries in Python 3. The table shows the names of the methods as well as information about their purpose.

Name Purpose
update Combining contents of two dictionaries into one
len Getting the size of
items Returns pairs (keys and values)
keys Returns keys
values Returns values
copy Copies the content into another dictionary
clear Clears all items
eval Convert string to dictionary

Related Posts

LEAVE A COMMENT