Python的字典函数介绍
发布时间:2023-12-07 12:53:31
在Python中,字典是用于存储键值对的数据结构。字典由一系列键和对应的值组成,可以根据键来访问对应的值。Python提供了一系列的字典函数,用于对字典进行操作和处理。下面是对一些常用的字典函数进行介绍:
1. clear():清空字典中的所有项。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
dict.clear()
print(dict) # 输出 {}
2. copy():返回字典的一个副本。
示例:
dict1 = {'Name': 'John', 'Age': 25, 'City': 'New York'}
dict2 = dict1.copy()
print(dict2) # 输出 {'Name': 'John', 'Age': 25, 'City': 'New York'}
3. get(key, default):根据键获取对应的值,如果键不存在则返回默认值。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
name = dict.get('Name')
country = dict.get('Country', 'Unknown')
print(name) # 输出 'John'
print(country) # 输出 'Unknown'
4. items():返回字典中所有的键值对。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
items = dict.items()
print(items) # 输出 dict_items([('Name', 'John'), ('Age', 25), ('City', 'New York')])
5. keys():返回字典中所有的键。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
keys = dict.keys()
print(keys) # 输出 dict_keys(['Name', 'Age', 'City'])
6. values():返回字典中所有的值。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
values = dict.values()
print(values) # 输出 dict_values(['John', 25, 'New York'])
7. pop(key, default):根据键删除字典中的项,并返回对应的值,如果键不存在则返回默认值。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
name = dict.pop('Name')
country = dict.pop('Country', 'Unknown')
print(name) # 输出 'John'
print(country) # 输出 'Unknown'
8. popitem():随机删除并返回字典中的一项(键值对)。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
item = dict.popitem()
print(item) # 输出 ('City', 'New York')
9. update(other_dict):将other_dict中的键值对更新到当前字典中。
示例:
dict1 = {'Name': 'John', 'Age': 25, 'City': 'New York'}
dict2 = {'Country': 'USA'}
dict1.update(dict2)
print(dict1) # 输出 {'Name': 'John', 'Age': 25, 'City': 'New York', 'Country': 'USA'}
10. len():返回字典中的键值对数量。
示例:
dict = {'Name': 'John', 'Age': 25, 'City': 'New York'}
length = len(dict)
print(length) # 输出 3
这些是一些常用的字典函数,在实际的编程中会经常用到。掌握了这些字典函数,可以更加方便地对字典进行操作和处理。
