Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

The concept of a dictionary

Dictionary data types in Python are much like real dictionaries in that they are organized together in key-value pairs (combinations of keys and values) that can be used to find and manipulate corresponding values. Just as each word (key) in a dictionary has a corresponding interpretation (value), each word and its interpretation together make an entry in a dictionary, and dictionaries often contain many such entries.

Create and use dictionaries

Creating dictionaries in Python uses the {} literal syntax, which is the same as creating collections. Each element consists of two values separated by:, which is preceded by a key and followed by a value. Each pair is separated by a comma. The syntax format is as follows:

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

Create a dictionary

# to create the 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' and 'ages' :' 19 '}Copy the code

Use dict() or dictionary generative syntax to create dictionaries, as in ↓

# Create objects with dict keys without "" quotes
dict1 = dict(name ="Sweet"Gender ="Female"Age ="19")
print(type(dict1), dict1)  # < class 'dict > {' name' : 'sweet', 'gender' : 'female' and 'ages' :' 19 '}

list1 = ["Name"."Gender"."Age"]
list2 = ["Sweet"."Female"."19"]
The # zip() function packages the corresponding elements of the object into tuples and returns an object composed of these tuples
dict2 = dict(zip(list1, list2))
print(dict2)  # {' name ': 'sweet ',' gender ': 'female ',' age ': '19'}


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

You can use Len (dict) to get the number of dictionary elements, the total number of keys

The for loop is also valid only for keys

dict1 = {'name': 'sweet'.'gender': 'woman'.'age': 'the'}
print(len(dict1))  # 3

for ch in dict1:
    print(ch)
Name Sex Age
Copy the code

Dictionary operation

Especially important for dictionaries are the member operations, which determine whether a given key is in the dictionary, and the index operations (which are keys in key-value pairs), which obtain the corresponding value, modify it, or add it. Keys in dictionaries must be immutable types, such as integer (int), float, string (STR), tuple, and so on. Dictionaries themselves are mutable types

The sample code

dict1 = {'name': 'sweet'.'gender': 'woman'.'age': 'the'}

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

# Judge before modifying
if "Name" in dict1:
    dict1["Name"] = 'Wang Tian Tian'
    print(dict1)  # {' name ': 'wang Tian Tian ',' gender ': 'female ',' age ': '19'}

Add data to dict1 through index
dict1["Hobby"] = "Travel"

print("Hobby" in dict1)  # True


Run a loop over the dictionary key to retrieve the value of the key
for key in dict1:
    print(f'{key}: {dict1[key]}')
Name: Wang Tiantian Gender: Female Age: 19 Hobby: traveling
Copy the code

Note that a KeyError exception is raised if the specified key is not in the dictionary when retrieving a value from an index operation

Dictionary method

Dictionary methods are all about manipulating key-value pairs

# dictionary nesting
students = {
    10001: {"name": "Xiao Ming"."sex": "Male"."age": 18},
    10002: {"name": "Little red"."sex": "Female"."age": 16},
    10003: {"name": "White"."sex": "Female"."age": 19},
    10004: {"name": "Chou"."sex": "Male"."age": 20}}# use the get method to get the corresponding value from the key. If not, return the default value (default: None).
print(students.get(10002))    # {'name': 'red ', 'sex':' female ', 'age': 16}
print(students.get(10005))    # None
print(students.get(10005."There is no such student"))    # There is no such student

Get all 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)

Delete the corresponding key-value pair by key using the pop method and return the value
stu1 = students.pop(10002)
print(stu1)             # {'name': 'red ', 'sex':' female ', 'age': 16}
print(len(students))    # 3
KeyError is raised if the deleted object is not in the dictionary
# stu2 = students.pop(10005) # KeyError: 10005


Remove the last set of key-value pairs from the dictionary using the popItem method and return the corresponding binary
# If there are no elements in the dictionary, calling this method raises KeyError
key, value = students.popitem()
print(key, value)    # 10004 {'name': '小周', 'sex': 'male ', 'age': 20}

# setDefault can update the values of keys in the dictionary or store new key-value pairs into the dictionary
The first argument to the # setDefault method is the key, and the second argument is the value of the key
If the key exists in the dictionary, updating the key will return the original value of the key
If the key does not exist in the dictionary, the method returns the value of the second argument, which defaults to None
result = students.setdefault(10005, {"name": "Little green"."sex": "Female"."age": 18})
print(result)        # {'name': 'age', 'sex': 'female ', 'age': 18}
print(students)      10001: # {{... }, (10003, {... }), 10005: {... }}

Use update to update dictionary elements. The same key overwrites the old value with the new value, and different keys are added to the dictionary
others = {
    10005: {"name": "Peony"."sex": "Male"."age": 19},
    10006: {"name": "The north"."sex": "Male"."age": 19},
    10007: {"name": "Little winter"."sex": "Male"."age": 19}
}
students.update(others)
10001: # {{... }, 10003: {... }, 10005: {... }, 10006: {... }, 10007: {... }}
print(students)
Copy the code