Dictionary public method

Posted by thepreacher on Sun, 23 Feb 2020 10:01:49 +0100

Dictionary public method

Dictionary introduction

Think about it:

If there is a list

nameList = ['xiaoZhang', 'xiaoWang', 'xiaoLi'];

You need to write the name "xiaoWang" wrong. Modify it by code:

nameList[1] = 'xiaoxiaoWang'

If the order of the list changes, as follows

nameList = ['xiaoWang', 'xiaoZhang',  'xiaoLi'];

At this time, you need to modify the subscript to complete the name modification

nameList[0] = 'xiaoxiaoWang'

Is there a way to not only store multiple data, but also locate the required element when it is convenient to access the element?
Answer:

Dictionaries

Another scenario:

Student information list, each student information including student number, name, age, etc., how to find a student's information?

>>> studens = [[1001, "king bao strong", 24], [1002, "Horse rong", 23], [1005,

<1> Dictionary in life


<2> Dictionary in software development

info = {'name':'Monitor', 'id':100, 'sex':'f', 'address':'Earth Asia Beijing, China'}

Explain:

Dictionaries, like lists, can store multiple data
When an element is found in the list, it is based on the subscript
When looking for an element in the dictionary, it is based on the 'name' (that is, the colon: the previous value, such as' name ',' id ',' sex 'in the code above)
Each element of the dictionary consists of two parts, key: value. For example, 'name': 'monitor', 'name' is the key, 'monitor' is the value

<3> Access values based on key

info = {'name':'Monitor', 'id':100, 'sex':'f', 'address':'Earth Asia Beijing, China'}

print(info['name'])
print(info['address'])

Result:

Monitor
 Earth Asia Beijing, China

If you access a key that does not exist, an error will be reported:

>>> info['age']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'age'

When we are not sure whether a key exists in the dictionary and want to get its value, we can use the get method and set the default value:

>>> age = info.get('age')
>>> age #The'age'key does not exist, so age is None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # If the key 'age' does not exist in info, the default value of 18 will be returned
>>> age
18

Common operation of Dictionary 1

<1> Modify element
The data in each element of the dictionary can be modified as long as it is found through the key

demo:

info = {'name':'Monitor', 'id':100, 'sex':'f', 'address':'Earth Asia Beijing, China'}

new_id = input('Please enter a new student number:')

info['id'] = int(new_id)

print('Modified id by: %d' % info['id'])

Result:

<2> Add element
demo: accessing non-existent elements

info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}

print('id by:%d' % info['id'])

Result:

>>> info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}
>>>
>>> print('id by:%d' % info['id'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'id'

If the key does not exist in the dictionary when using the variable name ['key'] = data, this element will be added.

demo: adding new elements

info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}

#print('id by:%d'%info['id'])#The program will run at the terminal because it accesses a key that does not exist

newId = input('Please enter a new student number:')

info['id'] = newId

print('Added id by:%d' % info['id'])

Result:

Please enter a new student number: 188
 The added id is: 188

<3> Delete element
There are several ways to delete a dictionary:

del
clear()
demo: del delete the specified element

info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}

print('Before deleting,%s' % info['name'])

del info['name']

print('After deletion,%s' % info['name'])

Result

>>> info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}
>>>
>>> print('Before deleting,%s' % info['name'])
//Before deleting,Monitor
>>>
>>> del info['name']
>>>
>>> print('After deletion,%s' % info['name'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'

demo: del delete entire dictionary

info = {'name':'monitor', 'sex':'f', 'address':'China'}

print('Before deleting,%s' % info)

del info

print('After deletion,%s' % info)

Result


demo: clear clears the entire dictionary

info = {'name':'monitor', 'sex':'f', 'address':'China'}

print('Before emptying,%s' % info)

info.clear()

print('After emptying,%s' % info)

Result

Common operation of dictionaries 2

<1>len()
Number of key value pairs in the measurement dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
print(len(dict01)) #3

<2>keys
Returns a list of all keys in the dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
keys = dict01.keys()
print(keys)   # ['name', 'age', 'sex']

<3>values
Returns a list of all value s in the dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
values = dict01.values()
print(values)  # ['Zhang San', 18, 'm']

<4>items
Returns a list of all (key, value) primitives

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
items = dict01.items()
print(items) # [('name ',' Zhang San '), ('age', 18), ('sex ',' m ')]

<5> Has_key (Python 3 has been cancelled, just learn)
dict.has_key(key) if the key is in the dictionary, it returns True, otherwise it returns False. Pay attention to running with python2

 -*- coding:utf-8 -*—
dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
dict01.has_key('name')  # True

ergodic

Through for in... We can traverse strings, lists, tuples, dictionaries, etc

Pay attention to the indentation of python syntax

String traversal

>>> a_str = "hello itcast"
>>> for char in a_str:
...     print(char,end=' ')
...
h e l l o   i t c a s t


List traversal

>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
...     print(num,end=' ')
...
1 2 3 4 5

Tuple traversal

>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
...     print(num,end=" ")
1 2 3 4 5

Dictionary traversal
<1> key of traversal dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
for key in dict01.keys():
    print(key)

//Result:
name
age
sex

<2> Traversal dictionary value

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
for value in dict01.values():
    print(value)

//Result:
//Zhang San
18
m

<3> Items (elements) traversing the dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
for item in dict01.items():
    print(item)

//Result:
('name', 'Zhang San')
('age', 18)
('sex', 'm')

<4> Key value of traversal dictionary

dict01 = {'name': 'Zhang San', 'age': 18, 'sex': 'm'}
for key, value in dict01.items():
    print('%s--%s' % (key, value))

//Result:
name--Zhang San
age--18
sex--m

Think about how to traverse index with subscript

>>> chars = ['a', 'b', 'c', 'd']
>>> i = 0
>>> for chr in chars:
...     print("%d %s"%(i, chr))
...     i += 1
...
0 a
1 b
2 c
3 d

enumerate()

The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, listing data and data subscripts at the same time, which is generally used in the for loop.

>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
...     print("%d %s"%(i, chr))
...
0 a
1 b
2 c
3 d

Public method

.+

>>> "hello " + "itcast"
'hello itcast'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

.*

>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

in

>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True

Note that when in operates the dictionary, it judges the key of the dictionary

python built-in functions
Python includes the following built-in functions

Serial number method description
 1. cmp(item1, item2) compares two values
 2. len(item) calculates the number of elements in the container
 3 max(item) returns the maximum value of the element in the container
 4 min(item) returns the minimum value of the element in the container
 5 del(item) delete variable

cmp

>>> cmp("hello", "itcast")
-1
>>> cmp("itcast", "hello")
1
>>> cmp("itcast", "itcast")
0
>>> cmp([1, 2], [3, 4])
-1
>>> cmp([1, 2], [1, 1])
1
>>> cmp([1, 2], [1, 2, 3])
-1
>>> cmp({"a":1}, {"b":1})
-1
>>> cmp({"a":2}, {"a":1})
1
>>> cmp({"a":2}, {"a":2, "b":1})
-1

Note: when comparing dictionary data, cmp compares keys first, and then values.

len

>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2

Note: len returns the number of key value pairs when operating dictionary data.

max

>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'

del
There are two ways to use del. One is del with spaces, the other is del()

>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Example of multidimensional list / ancestor access

>>> tuple1 = [(2,3),(4,5)]
>>> tuple1[0]
(2, 3)
>>> tuple1[0][0]
2
>>> tuple1[0][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range


>>> tuple1[0][1]
3
>>> tuple1[2][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range


>>> tuple2 = tuple1+[(3)]
>>> tuple2
[(2, 3), (4, 5), 3]
>>> tuple2[2]
3
>>> tuple2[2][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
Published 5 original articles, won praise 1, visited 217
Private letter follow

Topics: Python