Detailed explanation of dictionaries in Python
A dictionary in Python is an unordered collection of key-value pairs that is variable and has unique elements. The dictionary is represented by {}, each key-value pair is separated by a comma, and the key and value are connected by a colon. The keys in a dictionary must be of immutable type (such as strings, numbers, or tuples), while the values can be of any type.
Create dictionary
Create an empty dictionary:
my_dict = {}
Create a dictionary with key-value pairs:
my_dict = {'apple':5, 'banana':3, 'orange':2}
The dictionary supports dynamically adding and deleting key-value pairs , such as:
my_dict['pear'] = 4 del my_dict['orange']
Read the value of the dictionary
Read the value in the dictionary through the key. If the key does not exist, a KeyError exception will be thrown. For example:
# 读取存在的值 print(my_dict['apple']) # 输出 5 # 读取不存在的值 print(my_dict['grape']) # 抛出 KeyError 异常
Use the get method to avoid throwing exceptions. If the key does not exist, None or the specified default value will be returned. For example:
# 读取存在的值 print(my_dict.get('apple')) # 输出 5 # 读取不存在的值 print(my_dict.get('grape')) # 输出 None print(my_dict.get('grape', 0)) # 输出 0,因为指定了默认值为0
Traversing a dictionary
There are many ways to traverse a dictionary in Python.
for key, value in my_dict.items(): print(key, value)
for key in my_dict.keys(): print(key)
for value in my_dict.values(): print(value)
Commonly used dictionary methods
In addition to the above methods of reading values and traversing the dictionary, dictionaries also have other commonly used methods, as follows:
my_dict.clear()
new_dict = my_dict.copy()
my_dict.pop('apple')
new_dict = {'grape':1, 'pear':3} my_dict.update(new_dict)
Summary
Introduction to this article Learn about dictionaries in Python, including dictionary creation, reading values, traversing dictionaries and common methods. Dictionary is one of the very important and commonly used data structures in Python. Mastering dictionary operations is one of the basic skills of Python programming.
The above is the detailed content of Detailed explanation of dictionaries in Python. For more information, please follow other related articles on the PHP Chinese website!