Basic Operation of Python Dictionary

  • 2021-12-12 04:43:05
  • OfStack

Directory 1, Dictionary Concept 2, Dictionary Creation and Use 2.1 Dictionary Creation 3, Dictionary Operation 3.1 Dictionary Method

1. The concept of dictionary

Python The dictionary data type in is very similar to the real dictionary. It organizes the data into 1 in the way of key-value pair (combination of key and value), and the corresponding value can be found and operated by key. Just as every word (key) in a dictionary has a corresponding interpretation (value) 1, every word and its interpretation together is one entry in a dictionary, and a dictionary usually contains many such entries.

2. Create and use dictionaries

In Python Creating dictionaries in uses {} literal syntax, which is the same as creating symbols of collections. But the elements in the dictionary {} exist as key-value pairs, each consisting of two separated values, preceded by a key and followed by a value, with commas between each pair, splitting the syntax format,

The specific syntax format is as follows:


dict = {key1 : value1, key2 : value2 }

2.1 Creating a dictionary


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

dict2 = {
    " Name ": " Sweet ",
    " Gender ":  " Female ",
    " Age ": "19"
}
print(dict2)  # {' Name ': ' Sweet ', ' Gender ': ' Female ', ' Age ': '19'}

Use dict() Or the generative syntax of dictionaries, the example code is as follows:


#  Use dict  To create an object, the key cannot be added "" Quotation marks 
dict1 = dict( Name =" Sweet ",  Gender =" Female ",  Age ="19")
print(type(dict1), dict1)  # <class 'dict'> {' Name ': ' Sweet ', ' Gender ': ' Female ', ' Age ': '19'}

list1 = [" Name ", " Gender ", " Age "]
list2 = [" Sweet ", " Female ", "19"]
# zip() Function wraps the corresponding elements in the object into a 1 Each tuple, and returns an object composed of these tuples 
dict2 = dict(zip(list1, list2))
print(dict2)  # {' Name ': ' Sweet ', ' Gender ': ' Female ', ' Age ': '19'}


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

You can use the len(dict) Get the number of dictionary elements, that is, the total number of keys

for loops are also valid only for keys


dict1 = {' Name ': ' Sweet ', ' Gender ': ' Female ', ' Age ': '19'}
print(len(dict1))  # 3

for ch in dict1:
    print(ch)
'''
 Name 
 Gender 
 Age 
'''

3. Dictionary operation

For dictionaries, member operations and index operations (the index of a dictionary is the key in a key-value pair) are particularly important. The former can judge whether the specified key is in the dictionary, while the latter can get the corresponding value, modify it or add it. Keys in the dictionary must be of an immutable type, such as an integer ( int ), floating-point numbers ( float ), the string ( str ), tuples ( tuple ). The dictionary itself is also a mutable type

Sample code:


dict1 = {' Name ': ' Sweet ', ' Gender ': ' Female ', ' Age ': '19'}

#  Member operation 
print(" Name " in dict1, " Gender " not in dict1)  # True False

#  Judge first that you are modifying 
if " Name " in dict1:
    dict1[" Name "] = ' Wang Tiantian '
    print(dict1)  # {' Name ': ' Wang Tiantian ', ' Gender ': ' Female ', ' Age ': '19'}

#  By index for dict1  Adding data 
dict1[" Hobbies "] = " Tourism "

print(" Hobbies " in dict1)  # True


#  The dictionary keys are subjected to cyclic parallel index operation to obtain the corresponding values of the keys 
for key in dict1:
    print(f'{key}: {dict1[key]}')
'''
 Name :  Wang Tiantian 
 Gender :  Female 
 Age : 19
 Hobbies :  Tourism 
'''

Note: An KeyError exception will be thrown if the specified key is not in the dictionary when retrieving the value in the dictionary through an index operation

3.1 Dictionary Method

Dictionary methods are all related operations on key-value pairs:


#  Nesting of dictionaries 
students = {
    10001: {"name": " Xiao Ming ", "sex": " Male ", "age": 18},
    10002: {"name": " Xiao Hong ", "sex": " Female ", "age": 16},
    10003: {"name": " Xiaobai ", "sex": " Female ", "age": 19},
    10004: {"name": " Xiao Zhou ", "sex": " Male ", "age": 20}
}

#  Use get Method gets the corresponding value through the key. If it cannot be obtained, it will return the default value (the default is None ) 
print(students.get(10002))    # {'name': ' Xiao Hong ', 'sex': ' Female ', '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 by key and returns the value 
stu1 = students.pop(10002)
print(stu1)             # {'name': ' Xiao Hong ', 'sex': ' Female ', 'age': 16}
print(len(students))    # 3
#  If the deleted one is not in the dictionary, it will be thrown KeyError Anomaly 
# stu2 = students.pop(10005)    # KeyError: 10005


#  Use popitem Method deletes the last 1 Group key-value pairs and return the corresponding 2 Tuple 
#  If there are no elements in the dictionary, calling this method will throw KeyError Anomaly 
key, value = students.popitem()
print(key, value)    # 10004 {'name': ' Xiao Zhou ', 'sex': ' Male ', 'age': 20}

# setdefault You can update the values corresponding to keys in the dictionary or store new key-value pairs in the dictionary 
# setdefault The first of the method 1 The parameters are keys, and the 2 Parameters are the values corresponding to keys 
#  If this key exists in the dictionary, updating this key will return the original value corresponding to this key 
#  If this key does not exist in the dictionary, the method returns the 2 The value of the parameter, which defaults to None
result = students.setdefault(10005, {"name": " Little green ", "sex": " Female ", "age": 18})
print(result)        # {'name': ' Little green ', 'sex': ' Female ', 'age': 18}
print(students)      # {10001: {...}, (10003, {...}), 10005: {...}}

#  Use update Update dictionary elements, the same key will overwrite the old value with the new value, and different keys will be added to the dictionary 
others = {
    10005: {"name": " Xiaonan ", "sex": " Male ", "age": 19},
    10006: {"name": " Xiaobei ", "sex": " Male ", "age": 19},
    10007: {"name": " Xiao Dong ", "sex": " Male ", "age": 19}
}
students.update(others)
# {10001: {...}, 10003: {...}, 10005: {...}, 10006: {...}, 10007: {...}}
print(students)

Related articles: