欢迎访问宙启技术站
智能推送

Python字典函数:利用字典函数轻松操作字典

发布时间:2023-06-12 06:56:32

Python中的字典是一种非常常用的数据类型,它以键值对的形式存储数据,并且可以根据键名快速查找对应的值。在实际开发中,我们通常会对字典进行一些操作,比如添加、修改、删除、遍历等。Python也提供了很多内置的字典函数,可以帮助我们更加轻松地操作字典,提高编程效率。本文中,我们将介绍一些常见的字典函数及其用法,希望能够帮到大家。

1. len()函数

len()函数可以返回字典中键值对的数量。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(len(dic))  # 输出结果为 3

2. clear()函数

clear()函数可以清空字典中的所有键值对。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
dic.clear()
print(dic)  # 输出结果为 {}

3. copy()函数

copy()函数可以复制一个字典。例如:

dic1 = {'name':'Tom', 'age':18, 'gender':'male'}
dic2 = dic1.copy()
print(dic2)  # 输出结果为 {'name':'Tom', 'age':18, 'gender':'male'}

4. get()函数

get()函数可以根据键名获取对应的值,如果键名不存在,则返回默认值。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.get('name'))  # 输出结果为 'Tom'

print(dic.get('height', 170))  # 输出结果为 170,键名'height'不存在,默认返回170

5. items()函数

items()函数返回一个包含字典所有键值对的元组序列。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.items())  # 输出结果为 dict_items([('name', 'Tom'), ('age', 18), ('gender', 'male')])

6. keys()函数

keys()函数返回一个包含字典所有键的列表。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.keys())  # 输出结果为 ['name', 'age', 'gender']

7. values()函数

values()函数返回一个包含字典所有值的列表。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.values())  # 输出结果为 ['Tom', 18, 'male']

8. pop()函数

pop()函数可以删除字典中指定键名的键值对,并返回对应的值。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.pop('age'))  # 输出结果为 18
print(dic)  # 输出结果为 {'name':'Tom', 'gender':'male'}

9. popitem()函数

popitem()函数可以随机删除字典中的一个键值对,并返回对应的键值对。例如:

dic = {'name':'Tom', 'age':18, 'gender':'male'}
print(dic.popitem())  # 输出结果为 ('gender', 'male')
print(dic)  # 输出结果为 {'name':'Tom', 'age':18}

10. setdefault()函数

setdefault()函数可以根据指定的键名获取对应的值,如果键名不存在,则将键名和默认值添加到字典中。例如:

dic = {'name':'Tom', 'age':18}
print(dic.setdefault('gender', 'male'))  # 输出结果为 'male'
print(dic)  # 输出结果为 {'name':'Tom', 'age':18, 'gender':'male'}

print(dic.setdefault('age', 20))  # 输出结果为 18,键名'age'已存在,返回原值18不添加
print(dic)  # 输出结果为 {'name':'Tom', 'age':18, 'gender':'male'}

总结

本文介绍了一些常见的Python字典函数,这些函数可以帮助我们更加轻松地操作字典,在实际开发中非常有用。需要注意的是,有些函数会改变原字典,有些函数则会返回新的结果,我们在使用时需要根据具体情况进行选择。希望本文对大家能够有所帮助,同时也欢迎大家留言交流。