Python learning road-----dictionary operations

dictionary

A dictionary is a mutable container type and can store objects of any type

Each key-value pair of a dictionary is separated by a colon (:), and each pair is separated by a comma (,). The entire dictionary is enclosed in curly brackets ({}), and the format is as follows:

dict  =  { key1 : value , key2 : value2 , . . . . . }
  • 1

Keys must be unique, but values ​​do not

Values ​​can take any data type, but keys can only take constant data types (tuple, string, number)

create dictionary

my_dict =  { 'name'  :  'YWH' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] }
  • 1

access value in dictionary

Put the corresponding key of the value to be accessed in square brackets [ ]

#If you access a key that is not in the dictionary, the output error is as follows:

Traceback ( most recent call last ) : 
  File "test.py" , line 5 ,  in  < module > 
    print  ( "dict['Alice']: " ,  dict [ 'Alice' ] ) 
KeyError :  'Alice'
  • 1
  • 2
  • 3
  • 4
my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] } 
print ( 'My name is %s:' % my_dict [ 'name ' ] ) 
print ( 'My year is %d:' % my_dict [ 'year' ] ) 
if my_dict [ 'gender' ]  ==  1 :
	print ("I am a Boy!" ) 
else 
	print ( 'I am a Girl!' )
	
'''
My name is Yuwenhao
My year is 21
I am a Boy!
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Modify the dictionary

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] } 
print ( 'My year is %d:' % my_dict [ 'year ' ] )

my_dict [ 'year' ]  =  22 
my_dict [ 'School' ]  =  'HZAU' 
print ( 'Now, My year is %d:' % my_dict [ 'year' ] ) 
print ( 'My school is %s:' % my_dict [ 'School' ] )

'''
My year is 21:
Now, My year is 22:
My school is HZAU:
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

delete dictionary

Can delete a single element and empty the dictionary

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] }

del my_dict [ 'name' ] 
my_dict . clear ( )    # clear a dictionary 
print ( my_dict )

del my_dict
 print ( my_dict )     # delete a dictionary

'''
{}    
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 8, in <module>
    print(my_dict)
NameError: name 'my_dict' is not defined
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

dictionary key

1) Dictionaries do not allow the same key to appear twice . If a key is assigned twice during creation, the latter value will be remembered

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] , 'name' : 'YWH' }

print ( "my name is" , my_dict [ 'name' ] ) 
print ( "my dist is" , my_dict ) 
'''
my name is YWH
my dist is {'name': 'YWH', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2) The key must be an immutable data type

error_dist =  { [ 'name' ]  :  'Ywh' } 
print ( "my name is" , error_dist [ 'name' ] )

'''
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 1, in <module>
    error_dist = {['name'] : 'Ywh'}
TypeError: unhashable type: 'list'
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Dictionary built-in functions

len(dict) calculates the number of dictionary elements (number of keys)

str(dict) outputs a dictionary, represented as a printable string

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] }

str ( my_dict )

'''
"{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}"
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

dictionary method

dict.clear() deletes all elements in the dictionary

dict.copy() returns a shallow copy of the dictionary

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] }

copy_dict =  { } 
copy_dict = my_dict . copy ( )

print ( copy_dict )

'''
{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

dict.fromkeys(seq, value) creates a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and value as the initial value corresponding to all keys in the dictionary, the default is None

my_dict =  { } 
seq =  ( 'name' , 'year' , 'gender' ) 
my_dict = my_dict . fromkeys ( seq ) 
print ( my_dict ) 
my_dict = my_dict . fromkeys ( seq , 100 ) 
print ( my_dict )

'''
{'name': None, 'year': None, 'gender': None}
{'name': 100, 'year': 100, 'gender': 100}
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

key in dict returns True if the key is in the dictionary

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Henan' , 'Zhengzhou' , 'Erqi' , 'Xinghuajie' , 169 ] }

print ( 'name'  in my_dict ) 
print ( 'color'  in my_dict )

'''
True
false
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

dict.items() returns a convenient array of (key, value) tuples as a list

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 ,  'address'  :  [ 'Xinghuajie' , 169 ] }

list  = my_dict.items ( ) _ _

print ( list )

'''
dict_items([('name', 'Yuwenhao'), ('year', 21), ('gender', 1), ('address', ['Xinghuajie', 169])])
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

dict.keys() returns an iterator that can be converted to a list using list()

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 } 
iterator = my_dict . keys ( ) 
print ( iterator ) 
iterator_list =  list ( my_dict . keys ( ) ) 
print ( iterator_list )

'''
dict_keys(['name', 'year', 'gender'])
['name', 'year', 'gender']
'''

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

dict.setdefault(key, default=None) is similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default

dict.update(dict2) updates the key-value pairs in dict2 to dict

dict.values() returns an iterator that can be converted to a list using list()

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 } 
iterator = my_dict . values ( ) 
print ( iterator ) 
iterator_list =  list ( my_dict . values ( ) ) 
print ( iterator_list )

'''
dict_values(['Yuwenhao', 21, 1])
['Yuwenhao', 21, 1]
'''

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

dist.pop(key,default) deletes the value corresponding to the key key given by the dictionary, and the return value is the deleted value. The key value must be given!! Otherwise, an error will be reported. If the key to be deleted does not exist, you need to add a default value, otherwise an error will be reported:

my_dict =  { 'name'  :  'Yuwenhao' ,  'year'  :  21 ,  'gender'  :  1 } 
print ( my_dict . pop ( 'name' ) ) 
print ( my_dict . pop ( 'color' , 'None' ) )

'''
Yuwenhao
None
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

dict.popitem() randomly returns and removes the last key and value pair in the dictionary

Tags: Python learning road-----dictionary operations

Topics in Python python

Related: Python learning road-----dictionary operations