Dict container for Python

Keywords: Python

5. Dict container for Python

5.1 what is dict

If the list of students' names corresponds to the list of students' grades one by one, we can also find the grades of each student through subscript.

names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
scores = [45, 60, 75, 86, 49]
index = 0
for name in names:
    score = scores[index]
    print('name = {}, score = {}'.format(name, score))
    index = index + 1

In fact, we can get such a mapping.

'Alice' ==> 45
'Bob' ==> 60
'Candy' ==> 75
'David' ==> 86
'Ellena' ==> 49

However, using two lists is always troublesome, especially after changing the order of one list, the other list also needs to be transformed, otherwise there may be a problem of mismatch.
python's dict is dedicated to saving this mapping. Using dict can easily save the mapping of "name" - > "score".
In dict, each item contains a key and a value. The key and value correspond to each other one by one. In solving the above problems, we can use the name as the key and the score as the value. The definition of dict is as follows:

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}

In the definition, we use curly braces {} to indicate that this is a dict, and then use colon: division between key and value, and the end of each group of key:value is represented by comma.

5.2 Python reads dict elements

dict provides the function of finding the corresponding value through the key. The corresponding value can be obtained through the form of d[key].

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49,
    'Gaven': 86
}
print(d['Bob']) # ==> 60
print(d['Alice']) # ==> 45

This is similar to list finding the corresponding element by subscript.
Recall that when using subscripts to access list elements earlier, errors will be caused when subscripts do not exist. The same is true in dict. Errors will also be caused when the corresponding key does not exist.

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49,
    'Gaven': 86
}
print(d['Dodo'])
# Throw exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Dodo'

It means that the key does not exist. Therefore, when we need to find the value through the key, we must first judge whether the key exists, and then use the above method to obtain the corresponding value to avoid errors.

if 'Alice' in d:
    print(d['Alice']) # ==> 45
if 'Dodo' in d: # Dodo doesn't exist, so we won't follow the following logic
    print(d['Dodo'])

In addition to using this method, there is another method to obtain the corresponding value through the key. This method will not cause errors. dict itself provides a get method. By passing the key as a parameter to the get method, you can obtain the corresponding value. When the key does not exist, no error will be reported, but None will be returned.

print(d.get('Alice')) # ==> 45
print(d.get('Dodo')) # ==> None

Because the code implementation through the get method is simpler and will not cause errors, it is more recommended to use the get method to obtain the elements of dict.

5.3Python add dict element

Dict is different from tuple. Dict is variable. We can add a new key value to dict at any time, such as dict for the score of last class:

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}

When you need to add Dodo and Mimi scores, you can use the assignment statement to add elements:

d['Mimi'] = 72
d['Dodo'] = 88
print(d)

In fact, value can be any type of element, such as list, tuple, etc. if Mimi's last two scores are 72 and 73 respectively and Dodo's last two scores are 88 and 90 respectively, you can use the assignment statement to add the list element to dict.

d['Mimi'] = [72, 73]
d['Dodo'] = [88, 90]
print(d)

After that, if Mimi's and Dodo's third scores are 75 and 90 respectively, you can first query the corresponding value through the key, and then add the third score to the value of list.

d['Mimi'].append(75)
d['Dodo'].append(90)
print(d)
d = dict()
d['Alice'] = []
d['Bob'] = []
d['Candy'] = []
d['Alice'].append(50)
d['Alice'].append(61)
d['Alice'].append(66)
d['Bob'].append(80)
d['Bob'].append(61)
d['Bob'].append(66)
d['Candy'].append(88)
d['Candy'].append(75)
d['Candy'].append(90)
print(d)

Operation results
{'Alice': [50, 61, 66], 'Bob': [80, 61, 66], 'Candy': [88, 75, 90]}

5.4 Python update dict element

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
d['Bob'] = 75
print(d)
# ==> {'Alice': 45, 'Bob': 75, 'Candy': 75, 'David': 86, 'Ellena': 49}

At this time, we found that Bob's score was 60, but now it has become 75 because d['Bob'] = 75.
Therefore, we find that this assignment statement actually has two functions:

  1. When the key does not exist, add the corresponding key: value element to dict.
  2. When the key exists, the dict will be updated to replace the original value with the new value.

Therefore, when using assignment statements to add elements to dict, in order to avoid unnecessary coverage, we need to first judge whether the key exists, and then update it.

**Task: * * the scores of the students are as follows. Please update Alice's score to 60 and record the old scores.

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
old_score = d.get('Alice')
d['Alice'] = 60
print(old_score)

5.5 Python delete dict element

dict provides a convenient * * pop() method * * that allows us to quickly delete elements. The pop() method needs to specify the key of the element to be deleted and return the corresponding value.
Suppose Alice has transferred to another school and needs to delete Alice's grades, it can be written as follows:

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
print(d) # ==> {'Alice': 45, 'Bob': 60, 'Candy': 75, 'David': 86, 'Ellena': 49}
alice_score= d.pop('Alice')
print(alice_score) # ==> 45
print(d) # ==> {'Bob': 60, 'Candy': 75, 'David': 86, 'Ellena': 49}

It should be noted that the parameter of pop() method is the key in dict. When the key does not exist, it will also cause an error. For example, in the above operation, Alice's score has been deleted. If pop('Alice ') again, an error will be caused.

d.pop('Alice')
# report errors
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Alice'

task

In dict, you can use the keys() method to return all keys of dict. When deleting an element, you can first judge whether an element exists. Please modify the previous program so that even if the key does not exist, the deletion will not throw exceptions.

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
name = 'Alice'
if name in d.keys():
    d.pop(name)
else:
    print('{} not in d'.format(name))

5.6 features of Python Dict

Fast search speed

The first feature of dict is fast search speed. No matter whether dict has 10 elements or 100000 elements, the search speed is the same. The search speed of list decreases gradually with the increase of elements.
However, the fast search speed of dict is not without cost. The disadvantage of dict is that it occupies a large amount of memory and wastes a lot of content. On the contrary, list occupies a small amount of memory, but the search speed is slow.

Orderly or Unorderly

Before Python 3.5, the elements in dict were out of order, that is, the insertion order of elements in dict may not be consistent with the printing order. For example, execute the following code using the version before Python 3.5:

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
print(d) # ==> {'Bob': 60, 'Ellena': 49, 'Alice': 45, 'Candy': 75, 'David': 86}

You can see that the printing order is inconsistent with the defined order.
However, in Python 3.6 and python 3.7, orderly results are obtained.

print(d) # ==> {'Alice': 45, 'Bob': 60, 'Candy': 75, 'David': 86, 'Ellena': 49}

Because the underlying implementation has changed, we can think that dict is orderly after Python 3.6, but generally speaking, in order to avoid unnecessary misunderstandings, we will use a dictionary called Ordereddict to ensure order when ordered dict is required.

key immutable

For basic data types, strings and numbers, these are immutable and can be used as the key of dict. For complex data types, we know that tuple is immutable and list is variable. Therefore, tuple can be used as the key of dict, but list cannot be used as the key of dict, otherwise an error will be reported.

key = (1, 2, 3) # Take tuple as key
d[key] = True
key = [1, 2, 3]
d[key] = True
# report errors
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

As shown above, using list as the key of dict will cause an error.
Because dict searches by key, keys cannot be repeated in a dict.

Python traversal dict

Through direct print(d), we print out a complete dict; Sometimes, we need to print out the elements with m certain conditions in the dict, such as those with scores over 60. In this case, we need to traverse the dict (in this case, we need to use the for loop) and print out the elements that meet the conditions through condition judgment.
There are two ways to traverse dict. The first is to traverse all keys of dict and obtain the corresponding value through the key.

d = {
    'Alice': 45,
    'Bob': 60,
    'Candy': 75,
    'David': 86,
    'Ellena': 49
}
for key in d: # Traverse the key of d
    value = d[key]
    if value > 60:
        print(key, value)
# ==> Candy 75
# ==> David 86

The second method is the items() method provided by dict. The items() method will return all the elements in dict, and each element contains key and value.

for key, value in d.items():
    if value > 60:
        print(key, value)
# ==> Candy 75
# ==> David 86

5.7 other methods for Python to operate dict

Get all key s of dict

Dict provides the keys() function, which can return all keys in dict.

d = {'Alice': [50, 61, 66], 'Bob': [80, 61, 66], 'Candy': [88, 75, 90]}
for key in d.keys():
    print(key)
# ==> Alice
# ==> Bob
# ==> Candy

Get all value s of dict

Dict provides the values() function, which can return all values in dict.

d = {'Alice': [50, 61, 66], 'Bob': [80, 61, 66], 'Candy': [88, 75, 90]}
for key in d.values():
    print(key)
# ==> [50, 61, 66]
# ==> [80, 61, 66]
# ==> [88, 75, 90]

Clear all elements

Dict provides the clear() function, which can directly clear all elements in dict.

d = {'Alice': [50, 61, 66], 'Bob': [80, 61, 66], 'Candy': [88, 75, 90]}
print(d) # ==> {'Alice': [50, 61, 66], 'Bob': [80, 61, 66], 'Candy': [88, 75, 90]}
d.clear()
print(d) # ==> {}

Notes learn from moke.com Python 3 introductory tutorial 2020 new version

Posted by Poofman on Sun, 24 Oct 2021 06:39:34 -0700