dict#

Allow to build arrays that has key<->value relationship.

get extract element#

By using this function you can get value by key from the dict.

Purpose#

It may not be clear why this is necessary, as there is a [] operator which allows you to perform exactly the same actions. The difference from the [] operator is that it doesn’t cause an error if there is no specified key in the dictionary.

So the following cells show that the [] operator caused an error when you tried to load a non-existent key, but in the identical example the get method just returned None.

test_dict = {"a":1, "b":2}
print(test_dict["c"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[1], line 2
      1 test_dict = {"a":1, "b":2}
----> 2 print(test_dict["c"])

KeyError: 'c'
test_dict = {"a":1, "b":2}
print(test_dict.get("c"))
None

default argument#

Allows to set value to be returned If there is no item with the requested key.

test_dict = {"a":1, "b":2}
print(test_dict.get("c", "default value"))
default value

Delete specific item#

del operator#

You can simply apply the del operator to the specific element. As in the following example:

test_dict = {"a":1, "b":2}
del test_dict["a"]
print(test_dict)
{'b': 2}

Note If there is no item in the dict that you want to delete in this way, you will get the error. The next cell shows exactly this case:

test_dict = {"a":1, "b":2}
del test_dict["c"]
print(test_dict)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[5], line 2
      1 test_dict = {"a":1, "b":2}
----> 2 del test_dict["c"]
      3 print(test_dict)

KeyError: 'c'

pop method#

It will remove element by key passed as an argument to this method and return value as a result of the function. The following example shows how it works:

  • In the first print we show the result of the pop method;

  • In the second part, we’ll show that the dictionary no longer has an element with the key “a”.

test_dict = {"a":1, "b":2}
print(test_dict.pop("a"))
print(test_dict)
1
{'b': 2}

Note this method will still cause an error if you apply it to a key that doesn’t exist in the dictionary.

test_dict = {"a":1, "b":2}
test_dict.pop("C")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[7], line 2
      1 test_dict = {"a":1, "b":2}
----> 2 test_dict.pop("C")

KeyError: 'C'

clear delete all#

This method allows you to delete all the values written in the dictionary. The following example shows what it can look like.

test_dict = {"a":1, "b":2}
test_dict.clear()
print(test_dict)
{}

in operator#

Checks if the element on the left side of in is in the keys (not values) of the dictionary on the right side of in.

test_dict = {"a":1, "b":2}
print("a" in test_dict)
print(1 in test_dict)
True
False

Insert values#

There is a really trivial way to add new key:value combinations to the dictionary:

my_dict = {"a":5}
my_dict["b"] = 8
my_dict
{'a': 5, 'b': 8}

But there are some options to make it for group of the elements. We will consider them below.

update method#

Allows values to be added to the calling instance. If there are some identical keys - values, they would be taken from the argument dictionary.

dict1 = {"a":5, "c" : 10}
dict2 = {"b":7, "e" : 14, "a":3}
dict1.update(dict2)
dict1
{'a': 3, 'c': 10, 'b': 7, 'e': 14}

| operator#

Placed between two dictionaries will return a dictionary that has items from both dictionaries. The keys from the right dictionary taking precedence.

dict1 = {"a":5, "c" : 10}
dict2 = {"b":7, "e" : 14, "a":3}
dict1 | dict2
{'a': 3, 'c': 10, 'b': 7, 'e': 14}

** operator#

You can unpack dictionaries that you want to merge by using ** to create a new dictionary that contains both original dictionaries. The keys from the later dictionary taking precedence.

dict1 = {"a":5, "c" : 10}
dict2 = {"b":7, "e" : 14, "a":3}
{**dict1, **dict2}
{'a': 3, 'c': 10, 'b': 7, 'e': 14}

Key of max#

It was a common task for me to find a key of dict that matches the max/min value of the dictionary. The most elegant solution I found is to use dict as an argument for the max/min basic Python function, but as key argument use the dict.get method.

The logic is as follows - the function will iterate over the dictionary keys, and use only the results of execution of the function passed as an argument to the key parameter for comparison. Since we pass to the get function the corresponding value to the key, the comparison will be performed on the values of the dictionary.

So in the following example, I apply this solution to the randomly generated dictionary:

from random import randint
from IPython.display import HTML

example_dict = {
    chr(iscii_code): randint(0,10)
    for iscii_code in range(ord("a"), ord("g"))
}
display(HTML("<b style=\"font-size:120%\">=====Input dict=====</b>"))
display(example_dict)
display(HTML("<b style=\"font-size:120%\">=====Result=====</b>"))
display(HTML(max(example_dict, key=example_dict.get)))
=====Input dict=====
{'a': 3, 'b': 8, 'c': 6, 'd': 9, 'e': 6, 'f': 3}
=====Result=====
d