Python中字典的基础用法
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
Python Dictionary Advanced Usage Summary
This article provides a detailed introduction to advanced usage of dictionaries in Python, which are powerful data structures for storing and accessing key-value pairs efficiently.
Merging Dictionaries
In Python 3.5 and above, dictionaries can be merged using the **kwargs
syntax, and from Python 3.9 onwards, the union operator |
can be used for merging.
# Python 3.5+ dict1 = {"name": "Max", "age": 28} dict2 = {"city": "New York", "email": "max@xyz.com"} merged_dict = {**dict1, **dict2} # Python 3.9+ merged_dict = dict1 | dict2
Removing Elements from a Dictionary
The pop
function can be used to remove an element from a dictionary and it also returns the value of the removed key.
my_dict = {"name": "Max", "age": 28} value = my_dict.pop("age", "Key not found") print("Removed value:", value)
Iterating Over a Dictionary
There are multiple ways to iterate over a dictionary, including iterating over keys, values, or both keys and values.
# Iterating over keys for key in my_dict.keys(): print(key) # Iterating over values for value in my_dict.values(): print(value) # Iterating over both keys and values for key, value in my_dict.items(): print(key, value)
Copying a Dictionary
When copying a dictionary, it is important to use the copy()
method or the dict()
function to create a true copy, not just a reference.
my_dict = {"name": "Max", "age": 28} dict_copy = my_dict.copy() # Or dict_copy = dict(my_dict)
Nested Dictionaries
Dictionaries can contain any type of data as values, including another dictionary, known as nested dictionaries.
nested_dict = {"dictA": {"name": "Max", "age": 28}, "dictB": {"name": "Alex", "age": 25}}
Accessing and Updating Nested Dictionaries
Access or update values in nested dictionaries using consecutive square brackets []
or the get()
method.
nested_dict = {"dictA": {"name": "Max", "age": 28}} # Accessing print(nested_dict["dictA"]["name"]) # Output: Max # Updating nested_dict["dictA"]["age"] = 29 print(nested_dict) # Output: {'dictA': {'name': 'Max', 'age': 29}}
Accessing Dictionary Items with get()
Method
The get()
method allows safe access to dictionary items, returning a default value if the key does not exist, instead of raising a KeyError exception.
original_dict = {"a": 1, "b": 2, "c": 3, "d": 4} value1 = original_dict.get("c", "No corresponding data") value2 = original_dict.get("e", "No corresponding data") print(value1) # Output: 3 print(value2) # Output: No corresponding data
Accessing and Updating Data with setdefault()
Method
The setdefault()
method is similar to get()
but also adds the key with the default value to the dictionary if it does not exist.
original_dict = {"a": 1, "b": 2, "c": 3, "d": 4} original_dict.setdefault("e", 5) print(original_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
想要了解更多内容?