Python learning notes (7) dictionary

Eight, dictionary

The dictionary is the only mapping type in Python, which is stored as key value pair

1. Create dictionary

Dictionaries can be created in many forms. They are also indexed by brackets like lists, but not by subscripts but by keys.
Some dictionary creation methods are listed below

(1) Create with curly braces

Dictionaries can be created with curly braces, with each key value pair in the form of < key: value >

dict1 = {'Harry':'ExpelliArmus', 'Ron':'Bloody hell', 'Naruto':'Rasengan', 'August':'???'}
print('Ron said:', dict1['Ron'])

//Output result: Ron said: Blood shell

(2) Using keyword parameters and type constructors

dict2 = dict(name = 'August', gender = 'male') #The key before each value is a key parameter, not a string

//Output result: {'name': 'August', 'gender': 'male'}

(3) Using the type constructor and the zip() method

keys = ['1', '2', '3', '4']
values = ['one', 'two', 'three', 'four']
dict3 = dict(zip(keys, values))

//Output result: {'1':'one ',' 2 ':'two', '3':'three ',' 4 ':'Four'}

(4) Separate by field

dict4 = {} #Create an empty dictionary
dict4['name'] = 'FWTY'
dict4['nickName'] = 'August'
dict4['age'] = '23'

//Output results: {'name': 'FWTY', 'nickName': 'August', 'age': '23'}

(5) fromkeys()
The function of the fromkeys() method is also to create a new dictionary
The fromkeys() method does not operate on the dictionary itself but creates a new dictionary, so you need to assign the created dictionary to a variable

fromkeys(<keys> [,<values>]) #If not provided by velues, it defaults to None

dict5 = dict.fromkeys((1, 2, 3)) #Parameter values is empty

//Output result: {1: None, 2: None, 3: None}
dict5 = dict.fromkeys((1, 2, 3), 'Numbers')

//Output result: {1: 'numbers', 2:' numbers', 3: 'numbers'}

Note that the second parameter is treated as a whole by the fromkeys() method

dict5 = dict.fromkeys((1, 2, 3), ('one', 'two', 'three'))

//Output results: {1: ('one ',' two ',' three '), 2: ('one', 'two', 'three'), 3: ('one ',' two ',' three ')}
'''Because it is treated as a whole, it does not correspond each element in the tuple to each key as a different value, but takes the whole tuple as a value'''

2. ACCESS Dictionary

(1) keys()
The keys() method returns the dictionary key

dict1 = dict.fromkeys(('A', 'B', 'C', 'D'), 'Letters')
for eachKey in dict1.keys():
//Output result: A

(2) values()
The values() method returns the dictionary value

keys = ['1', '2', '3', '4']
values = ['one', 'two', 'three', 'four']
dict2 = dict(zip(keys, values))
for eachValue in dict2.values():

//Output result: one

(3) items()
The items() method returns the dictionary items (key value pairs)

keys = ['1', '2', '3', '4']
values = ['one', 'two', 'three', 'four']
dict2 = dict(zip(keys, values))
for eachItem in dict2.items():
//Output result: ('1 ','one')
        ('2', 'two')
        ('3', 'three')
        ('4', 'four')

(4) get()
The get() method is a more relaxed way to access dictionary items. When we directly use the key to index, if we access a nonexistent key, the program will report an error, such as:

dict3 = dict.fromkeys((1, 2, 3), 'Numbers')

Output result: KeyError: 4

But when we use the get() method, accessing a key that does not exist does not report an error.

Get (< key > [, < return value when key does not exist >]) ා the second parameter is optional, and when it is not filled in, it returns None by default

dict3 = dict.fromkeys((1, 2, 3), 'Numbers')

Output result: None
print(dict3.get(4, 'Dont Exist'))

Output result: Don exist

3. Common methods

(1) clear()
The clear() method is used to clear the dictionary


Output: {}

(2) copy()
The copy() method is a shallow copy

Shallow copy only copies the pointer to an object, not the object itself. The new and old objects still share the same block of memory. But deep copy as like as two peas will create another object. The new object does not share memory with the original object. Modifying the new object will not change the original object.

If the elements in the copied object have only values and no references, there is no difference between the shallow copy and the deep copy. The original object will be copied and a new object will be generated. Modifying the values in the new object will not affect the original object, and the new object and the original object will be completely separated.

If the elements in the copied object contain references (like another list stored in one list, which is the reference of another list), the shallow copy is different from the deep copy. Although the shallow copy copies the original object, it still saves the references. Therefore, modifying the values in the references in the new object will still change the values in the list in the original object , the new object and the original object are completely separated and not completely separated. But the deep copy is different. It will create a new reference in the original object, that is, create a new list, and then place the reference of the new list, so that the new object and the original object can be completely separated.

The direct assignment is the reference of the object

Simple example:
​ a = {1 : '123'}

  • b=a directly assigns a, b points to the same object

  • b = a.copy() copies a shallowly. B is two independent objects, but their children also point to the same object (a reference to the same object)

  • b = copy.deep copy (a) the deep copy b completely copies the parent object and its child object of a, which are completely independent

(3) pop() / popitem()
The pop() method pops up a dictionary entry and returns its value

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

//Output result: two ා return the value of dictionary item with key 2
        {1: 'one', 3: 'three', 4: 'four'}

The popitem() method pops up the last dictionary item and returns

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

//Output result: (4, 'four')
        {1: 'one', 2: 'two', 3: 'three'}

(4) setdefault()
The function of setdefault() method is to find the corresponding value according to the key. If the key queried does not exist, it will be added to the dictionary

setdefault(<key>[, <value>]) #If no value is specified, the corresponding value of the added key is None

dict2 = {1:'one', 2:'two', 3:'three', 4:'four'}
print(dict2.setdefault(6, 'six'))

//Output result: one query key value pair exists
        None #No value corresponding parameter is set
        six #Set the value corresponding parameter
        {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None, 6: 'six'}

(5) update
The update() method is used to update the dictionary with a dictionary (or mapping relationship)

dict2 = {1:'one', 2:'two', 3:'three', 4:'four'}
dict3 = {4:'Four'}

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

Tags: Python shell

Posted on Thu, 19 Mar 2020 08:46:50 -0400 by swimmerphil1