温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python字典操作有哪些

发布时间:2021-12-17 15:01:54 来源:亿速云 阅读:129 作者:iii 栏目:大数据

这篇文章主要介绍“python字典操作有哪些”,在日常操作中,相信很多人在python字典操作有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”python字典操作有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

key是否存在


使用 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": 0}
# 按照value排序
>>> sorted(d.items(), key=operator.itemgetter(1))
[('b', 0), ('a', 1), ('c', 3), ('f', 6)]
# 按照key排序
>>> sorted(d.items(), key=operator.itemgetter(0))
[('a', 1), ('b', 0), ('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] = 0
...
>>> data
{'a': 1, 'b': 0, 'c': 1, 'd': 0}

可以使用 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字典操作有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI