current position:Home>Python notes (IX): basic operation of dictionary

Python notes (IX): basic operation of dictionary

2022-01-30 10:41:14 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

The concept of a dictionary

Python The dictionary data type in is very similar to the dictionary in reality , It is based on key value pairs ( Combination of key and value ) Organize data together in a way , The corresponding value can be found and operated through the key . Just like every word in the dictionary ( key ) There will be corresponding explanations ( value ) equally , Each word, together with its interpretation, is an entry in the dictionary , The dictionary usually contains many such entries .

Creating and using dictionaries

stay Python Create a dictionary in {} Literal grammar , This is the same set of symbols created by . But the dictionary {} The elements in exist in the form of key value pairs , Each element consists of : Two separated values form ,: The front is the key : After that is the value , Use commas... Between each pair , Split syntax format , The specific syntax is as follows :

dict = {key1 : value1, key2 : value2 }
 Copy code 

Create a dictionary

#  Create a dictionary 
dict1 = {" full name ": " Sweet "}
print(type(dict1), dict1)  # <class 'dict'> {' full name ': ' Sweet '}

dict2 = {
    " full name ": " Sweet ",
    " Gender ":  " Woman ",
    " Age ": "19"
}
print(dict2)  # {' full name ': ' Sweet ', ' Gender ': ' Woman ', ' Age ': '19'}
 Copy code 

Use dict() Or the generative syntax of a dictionary to create a dictionary , Sample code ↓

#  Use dict  Create objects , Key cannot be added "" quotes 
dict1 = dict( full name =" Sweet ",  Gender =" Woman ",  Age ="19")
print(type(dict1), dict1)  # <class 'dict'> {' full name ': ' Sweet ', ' Gender ': ' Woman ', ' Age ': '19'}

list1 = [" full name ", " Gender ", " Age "]
list2 = [" Sweet ", " Woman ", "19"]
# zip() The function packages the corresponding elements in the object into tuples , Returns the object composed of these tuples 
dict2 = dict(zip(list1, list2))
print(dict2)  # {' full name ': ' Sweet ', ' Gender ': ' Woman ', ' Age ': '19'}


#  Create a dictionary using the generated columns 
dict3 = {x: x ** 3 for x in range(6)}
print(dict3)  # {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
 Copy code 

have access to len(dict) Get the number of dictionary elements , That's the total number of bonds

for Loops can only work with keys

dict1 = {' full name ': ' Sweet ', ' Gender ': ' Woman ', ' Age ': '19'}
print(len(dict1))  # 3

for ch in dict1:
    print(ch)
'''  full name   Gender   Age  '''
 Copy code 

Dictionary operations

For dictionaries , Member operation and index ( The index of a dictionary is the key in a key value pair ) Operation is particularly important , The former can judge whether the specified key is in the dictionary , The latter can get the corresponding value , Or modify it or add . The key in the dictionary must be of invariant type , For example, integers (int)、 Floating point numbers (float)、 character string (str)、 Tuples (tuple) And so on . The dictionary itself is also a variable type

Sample code

dict1 = {' full name ': ' Sweet ', ' Gender ': ' Woman ', ' Age ': '19'}

#  Members of the operation 
print(" full name " in dict1, " Gender " not in dict1)  # True False

#  First judge whether you are modifying 
if " full name " in dict1:
    dict1[" full name "] = ' Wang Tiantian '
    print(dict1)  # {' full name ': ' Wang Tiantian ', ' Gender ': ' Woman ', ' Age ': '19'}

#  By indexing dict1  Add data 
dict1[" hobby "] = " tourism "

print(" hobby " in dict1)  # True


#  The key of the dictionary is cycled and the value corresponding to the key is obtained through index operation 
for key in dict1:
    print(f'{key}: {dict1[key]}')
'''  full name :  Wang Tiantian   Gender :  Woman   Age : 19  hobby :  tourism  '''
 Copy code 

Be careful , When getting the value in the dictionary through index operation , If the specified key is not in the dictionary , Would trigger KeyError abnormal

Dictionary method

The dictionary method is to perform relevant operations on key value pairs

#  Nesting of dictionaries 
students = {
    10001: {"name": " Xiao Ming ", "sex": " male ", "age": 18},
    10002: {"name": " Xiaohong ", "sex": " Woman ", "age": 16},
    10003: {"name": " The small white ", "sex": " Woman ", "age": 19},
    10004: {"name": " Xiaozhou ", "sex": " male ", "age": 20}
}

#  Use get Method obtains the corresponding value through the key , If not, the default value is returned ( The default is None)
print(students.get(10002))    # {'name': ' Xiaohong ', 'sex': ' Woman ', 'age': 16}
print(students.get(10005))    # None
print(students.get(10005, " Without this student "))    #  Without this student 

#  Get all the keys in the dictionary 
print(students.keys())      # dict_keys([10001, 10002, 10003, 10004])
#  Get all the values in the dictionary 
print(students.values())    # dict_values([{...}, {...}, {...}, {...}])
#  Get all key value pairs in the dictionary 
# dict_items([(10001, {...}), (10002, {....}), (10003, {...}), (10004, {...})])
print(students.items())
#  Loop through all key value pairs in the dictionary 
for key, value in students.items():
    print(key, '--->', value)

#  Use pop Method deletes the corresponding key value pair through the key and returns the value 
stu1 = students.pop(10002)
print(stu1)             # {'name': ' Xiaohong ', 'sex': ' Woman ', 'age': 16}
print(len(students))    # 3
#  Delete if not in the dictionary , May trigger KeyError abnormal 
# stu2 = students.pop(10005) # KeyError: 10005


#  Use popitem Method deletes the last set of key value pairs in the dictionary and returns the corresponding binary 
#  If there are no elements in the dictionary , Calling this method raises KeyError abnormal 
key, value = students.popitem()
print(key, value)    # 10004 {'name': ' Xiaozhou ', 'sex': ' male ', 'age': 20}

# setdefault You can update the value corresponding to the key in the dictionary or store a new key value pair in the dictionary 
# setdefault The first argument to the method is the key , The second parameter is the value corresponding to the key 
#  If this key exists in the dictionary , After updating this key, the original value corresponding to this key will be returned 
#  If this key doesn't exist in the dictionary , Method will return the value of the second parameter , The default is None
result = students.setdefault(10005, {"name": " Little green ", "sex": " Woman ", "age": 18})
print(result)        # {'name': ' Little green ', 'sex': ' Woman ', 'age': 18}
print(students)      # {10001: {...}, (10003, {...}), 10005: {...}}

#  Use update Update dictionary elements , The same key will overwrite the old value with the new value , Different keys will be added to the dictionary 
others = {
    10005: {"name": " Xiaonan ", "sex": " male ", "age": 19},
    10006: {"name": " Little North ", "sex": " male ", "age": 19},
    10007: {"name": " Xiaodong ", "sex": " male ", "age": 19}
}
students.update(others)
# {10001: {...}, 10003: {...}, 10005: {...}, 10006: {...}, 10007: {...}}
print(students)
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301041117829.html

Random recommended