Python字典作为一种灵活且常用的数据结构,其高效的创建、访问和操作方式在数据处理中扮演着重要角色。本文所述的技巧,不仅能提高代码的可读性,还能优化代码的性能。
一:使用
dict(key=value)
创建字典
使用
dict(key=value)
创建字典比
{}
方法更好:
d = {'apple':4, 'orange':5, 'pear':6, 'pineapple':7}
print(d)
d_dict = dict(apple=4, orange=5, pear=6, pineapple=7)
d_dict
二:合并字典使用 **
在字典前使用
**
会将键值对解包到父字典中。
a = {1:1, 2:2}
b = {3:3, 4:4}
x = {**a, **b}
print(x)
x = {**a, **b, 5:5}
print(x)
三:可以使用 ** 将字典作为关键字参数传递
**
放在字典前面,再次将其键值对解包到函数
test
中。如果我们希望动态地将关键字参数传递给函数,这个方法非常有用。
def test(a, b, c):
print(a, b, c)
test(a=1, c=2, b=3)
mydict = dict(a=1, b=2, c=3)
print(mydict)
test(**mydict)
四:字典推导式
字典推导式更加优雅、Python 化且更易于阅读。比如我们想要创建
{1:1, 2:4, 3:9, 4:16}
,下面的示例使用两种方式对比,字典推导式更优雅:
d = {}
for i in range ( 1 , 5 ):
d[i] = i** 2
print (d)
d = {i:i** 2 for i in range ( 1 , 5 )}
print (d)
五:值获取方式dict.get(key, default_value)
当我们访问一个不存在的键时,通常会出现 KeyError 错误 ;这里使用
dict.get(key, default_value)
方法可以避免 KeyError 错误。如果键不存在,它会返回
default_value
,而不是引发异常。
d = {1:1, 2:2, 3:3}
print(d[1])
print(d[4])