ITPub博客

首页 > 人工智能 > 自然语言 > Python 这10个字典操作你必须知道

Python 这10个字典操作你必须知道

自然语言 作者:小咖啡111 时间:2019-04-25 10:27:41 0 删除 编辑

  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 2c 4a 1

  也可以直接对字典z进行迭代,每次迭代返回的是key,前面那种操作 z.items()会返回一个新的对象。

  >>> for key in z: print(key, z[key])b 2c 4a 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(, {'a': 2, 'b': 1, 'c': 2, 'd': 1})

  defaultdict 是 dict 的子类,继承了 dict 的所有特性, 如果想要初始值为1 怎么办? 可以用lambda函数来指定

  dd = defaultdict(lambda: 1)for c in chars:dd[c] += 1print(dd)>>> defaultdict(<1function at 0x01226B28>, {'a': 3, 'b': 2, 'c': 3, 'd': 2})


Python学习交流群:519489681  备注:小白


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31560357/viewspace-2642470/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-10-31

  • 博文量
    66
  • 访问量
    77431