Data in a dictionary appears in key-value pairs and does not support indexing.
1 – Adding Data to a Dictionary
Syntax: dictionary[key] = value
If the key exists, modify the value of the key; if it does not exist, add this key-value pair.
dict1 = {"name": "Xiaomi", "age": 18}dict1["sex"] = "male"print(dict1) #{'name': 'Xiaomi', 'age': 18, 'sex': 'male'}dict1["sex"] = "female"print(dict1) #{'name': 'Xiaomi', 'age': 18, 'sex': 'female'}
2 – Deleting Data from a Dictionary
Syntax:
del(): Deletes the dictionary or deletes the specified key-value pair from the dictionary.
clear(): Clears the dictionary.
dict1 = {"name": "Xiaomi", "age": 18}del dict1["age"]print(dict1) #{'name': 'Xiaomi'}dict1.clear()print(dict1) #{}
3 – Searching in a Dictionary
1) Key lookup: If the key exists, return the corresponding value; otherwise, raise an error.
2) Function lookup
get(): If the key being searched does not exist, return the second parameter; if the second parameter is omitted, return None.
Syntax: dictionary.get(key, default_value)
keys()
values()
items()
dict1 = {"name": "Xiaomi", "age": 18}print(dict1["name"]) # Xiaomi#print(dict1["sex"]) # Errorprint(dict1.get("age")) # 18print(dict1.get("sex")) # Noneprint(dict1.keys()) # dict_keys(['name', 'age'])print(dict1.values()) # dict_values(['Xiaomi', 18])print(dict1.items()) # dict_items([('name', 'Xiaomi'), ('age', 18)])
4 – Iterating Over Dictionary KeysGet the key elements in the dictionary.
dict1 = {"name": "Xiaomi", "age": 18, "sex": "male"}for key in dict1.keys(): print(key) # name age sex
5 – Iterating Over Dictionary Values
dict1 = {"name": "Xiaomi", "age": 18, "sex": "male"}for value in dict1.values(): print(value) # Xiaomi 18 male
6 – Getting Key-Value Pairs
Returns an iterable object, where each item is a tuple containing two elements: the key and the value of the dictionary.
dict1 = {"name": "Xiaomi", "age": 18, "sex": "male"}for item in dict1.items(): # Returns an iterable object, where each item is a tuple containing two elements: the key and the value of the dictionary. print(item) # ('name', 'Xiaomi') ('age', 18) ('sex', 'male')
7 – Unpacking Key-Value Pairs
dict1 = {"name": "Xiaomi", "age": 18, "sex": "male"}for key, value in dict1.items(): # Returns an iterable object, where each item is a tuple containing two elements: the key and the value of the dictionary. print(key) print(value) print(f"{key}={value}")