首页 > 人工智能 > 机器学习 > Python 这10个字典操作你必须知道
使用
in
关键字判断key是否存在字典中
d = {
"name"
:
"zhang"
,
"age"
:
10
}
key =
"gender"
if
key
in
d:
pass
不要使用
key in d.keys()
, 这是一种画蛇添足的操作,因为d.keys()会返回一个新的列表对象,导致内存最大。
>>>
x = {
'a'
:
1
,
'b'
:
2
}
>>>
y = {
'b'
:
3
,
'c'
:
4
}
>>>
{**x, **y}
{
'a'
:
1
,
'b'
:
3
,
'c'
:
4
}
返回新的字典对象,x和y都不会改变,这是使用了PEP448范化解包操作, 如果 x 和 y 有相同的key, 那么y会覆盖x。 如果使用字典的
update
方法,将修改原来的对象,例如:
>>>
y.update(x)
>>>
y
{
'b'
:
2
,
'c'
:
4
,
'a'
:
1
}
z = {
'b'
:
2
,
'c'
:
4
,
'a'
:
1
}
>>>
for
key, value
in
z.items():
print(key, value)
b
2
c
4
a
1
也可以直接对字典z进行迭代,每次迭代返回的是key,前面那种操作 z.items()会返回一个新的对象。
>>>
for
key
in
z:
print(key, z[key])
b
2
c
4
a
1
使用字典推导式快速构建字典对象
>>>
fruits = [
'apple'
,
'mango'
,
'banana'
,
'cherry'
]
>>>
{f:len(f)
for
f
in
fruits}
{
'apple'
:
5
,
'mango'
:
5
,
'banana'
:
6
,
'cherry'
:
6
}
字典本质上是个无序的容器对象(其实Python3.6开始支持有序,不过这个有序是指按照key的添加顺序),如果我们要对字典的 key 或者 value 排序,一般是将其转换为list,再按照key或者value排序。
>>>
d = {
"c"
:
3
,
"a"
:
1
,
"f"
:
6
,
"b"
:
}
# 按照value排序
>>>
sorted(d.items(), key=operator.itemgetter(
1
))
[(
'b'
,
), (
'a'
,
1
), (
'c'
,
3
), (
'f'
,
6
)]
# 按照key排序
>>>
sorted(d.items(), key=operator.itemgetter(
))
[(
'a'
,
1
), (
'b'
,
), (
'c'
,
3
), (
'f'
,
6
)]
>>>
统计列表中每个字母出现的次数
>>>
chars = [
'a'
,
'b'
,
'c'
,
'a'
,
'd'
,
'c'
]
>>>
data = {}
>>>
for
c
in
chars:
...
if
c
in
data:
...
data[c]+=
1
...
else
:
...
data[c] =
...
>>>
data
{
'a'
:
1
,
'b'
:
,
'c'
:
1
,
'd'
:
}
可以使用 collections.defaultdict 通过工厂函数提供初始化默认值
chars = ['a', 'b','c','a','d','c']
dd = defaultdict(int)
for c in chars:
dd[c] += 1
>>>defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 2, 'd': 1})
defaultdict 是 dict 的子类,继承了 dict 的所有特性, 如果想要初始值为1 怎么办? 可以用lambda函数来指定
dd = defaultdict(
lambda
:
1
)
for
c
in
chars:
dd[c] +=
1
print(dd)
>>>
defaultdict(<function <
lambda
> at
0x01226B28
>, {
'a'
:
3
,
'b'
:
2
,
'c'
:
3
,
'd'
:
2
})
Python学习交流群:519489681 备注:小白爱踢
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31560357/viewspace-2643329/ ,如需转载,请注明出处,否则将追究法律责任。