Skip to content

Instantly share code, notes, and snippets.

@atlanmatrix
Created June 11, 2019 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atlanmatrix/5e7004ca28c3652e283bf718014b37db to your computer and use it in GitHub Desktop.
Save atlanmatrix/5e7004ca28c3652e283bf718014b37db to your computer and use it in GitHub Desktop.

字典操作

合并(四种方法)

通过.items()方法转化成tuple,相加再转化为dict

dict(dict_a.items() + dict_b.items())

通过update方法

a.update(b)

通过dict(a, **b)方法

dict(a, **b)

遍历

删除

通过键删除

d.pop(key)

全部删除

# 不会修改内存地址(不是重新赋值操作)
d.clear()

随机删除并返回删除的键值对

# 返回元组 (key, value)
d.popitem()

排序

字典是无序结构,但是 OrderedDict 是有序字典。在 python 3.7 版本后, dict 会记住键值对的插入顺序。 OrderedDict 实际上看起来就像是 d.items() 后的样子

dict(sorted(a.items(), key=lambda x:x[0], reverse=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment