Python字典是一种数据结构,它存储的是键值对(key-value pair)。在Python中,字典用于存储和组织数据,并且提供了快速查找和访问数据的方法。
以下是一些Python字典的基本操作:
创建字典:
# 创建一个空的字典
my_dict = {}# 创建一个包含键值对的字典
my_dict = {"key1": "value1","key2": "value2","key3": "value3"
}
添加键值对:
my_dict["key4"] = "value4"
获取值:
value = my_dict["key1"]
修改值:
my_dict["key1"] = "new value"
删除键值对:
del my_dict["key1"]
检查键是否在字典中:
if "key2" in my_dict:print("Key exists in dictionary")
获取字典的长度:
length = len(my_dict)
字典的遍历:
for key, value in my_dict.items():print(f"Key: {key}, Value: {value}")
字典的合并:
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}
字典的复制:
dict1 = {"a": 1, "b": 2}
dict2 = dict1.copy()
字典的排序:
dict1 = {"b": 2, "a": 1}
sorted_dict = dict(sorted(dict1.items()))
从字典中获取键值对:
items = dict1.items()
使用字典推导式创建字典:
nums = [1, 2, 3, 4, 5]
squares = {num: num**2 for num in nums}
清空字典:
dict1.clear()
使用get方法获取字典中的值,如果键不存在则返回默认值:
value = dict1.get("key", default_value)
字典中的键值对迭代:
dict1 = {"a": 1, "b": 2, "c": 3}
for key, value in dict1.items():print(f"Key: {key}, Value: {value}")
使用keys方法获取字典中的键:
keys = dict1.keys()
- 使用values方法获取字典中的值:
values = dict1.values()
使用items方法获取字典中的键值对:
items = dict1.items()
字典的嵌套:
dict1 = {"a": {"b": 1, "c": 2}, "d": {"e": 3, "f": 4}}
字典的递归:
def recursive_dict(dictionary, key):if isinstance(dictionary, dict):for k, v in dictionary.items():if k == key:return velif isinstance(v, dict):result = recursive_dict(v, key)if result is not None:return resultreturn None
字典中的键大小写转换:
dict1 = {"a": 1, "b": 2}
dict2 = {k.lower(): v for k, v in dict1.items()}
字典中的值大小写转换:
dict1 = {"a": "Hello", "b": "World"}
dict2 = {k: v.lower() for k, v in dict1.items()}
字典中的键值对反转:
dict1 = {"a": 1, "b": 2}
dict2 = {v: k for k, v in dict1.items()}
从列表中创建字典:
list1 = [("a", 1), ("b", 2), ("c", 3)]
dict1 = dict(list1)
从字典中提取键:
dict1 = {"a": 1, "b": 2, "c": 3}
keys = dict1.keys()
从字典中提取值:
dict1 = {"a": 1, "b": 2, "c": 3}
values = dict1.values()
字典中的键值对拆分:
dict1 = {"a": 1, "b": 2, "c": 3}
keys = [k for k in dict1]
values = [v for v in dict1.values()]
字典中的键值对合并:
keys = ["a", "b", "c"]
values = [1, 2, 3]
dict1 = dict(zip(keys, values))
字典中的值取最大值:
dict1 = {"a": 1, "b": 2, "c": 3}
max_value = max(dict1.values())
字典中的值取最小值:
dict1 = {"a": 1, "b": 2, "c": 3}
min_value = min(dict1.values())
字典的并集:
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}