前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python dict常用

python dict常用

作者头像
bear_fish
发布2018-09-14 09:47:18
5410
发布2018-09-14 09:47:18
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338335

本文主要是python中dict常用的方法:

  1. list 转化为 dict
  2. dict遍历删除指定条件的元素
  3. dict安装key或者value排序
  4. dict的value统计计数

两个list转化为dict

代码语言:javascript
复制
def lst_2_dict():
    """
    combine two list to dict
    :return:
    """
    lst1 = ['a', 'b', 'c']
    lst2 = [1, 2, 3]
    # d = {k: v for k, v in zip(lst1, lst2)}
    d = dict(zip(lst1, lst2))
    print d
    # {'a': 1, 'c': 3, 'b': 2}

删除dict中value < 0 的元素

代码语言:javascript
复制
def iter_dict_remove():
    """remove item in dict while iteration it"""
    d_info = {'aa': -1, 'bb': 0, 'cc': 1, 'dd': 2}

    for k in d_info.keys():
        print k, d_info[k]
        if d_info[k] < 0:
            del d_info[k]

    print 'after del', d_info 

按照key的顺序变量dict

代码语言:javascript
复制
def iter_dic_sort():
    """iter dict by sorted keys"""
    d_info = {'33': 33, '88': 88, '22': 22, '44': 44}
    for k in sorted(d_info):
        print k, d_info[k]

安装key或者value对dict排序:

代码语言:javascript
复制
def dict_sort_by_value():
    dic_num = {'first': 11, 'second': 2, 'third': 33, 'Fourth': 4}

    # print all the keys
    print dic_num.keys()
    print list(dic_num)
    # ['second', 'Fourth', 'third', 'first']

    # print all the sorted keys
    print sorted(dic_num)
    # ['Fourth', 'first', 'second', 'third']

    print sorted(dic_num, key=str.lower)
    # ['first', 'Fourth', 'second', 'third']

    # print sorted values
    print sorted(dic_num.values())
    # [2, 4, 11, 33]

    # sorted by value
    sorted_val = sorted(dic_num.items(), key=operator.itemgetter(1))
    # [('second', 2), ('Fourth', 4), ('first', 11), ('third', 33)]
    print sorted_val

    # sorted by key
    sorted_key = sorted(dic_num.items(), key=operator.itemgetter(0))
    print sorted_key
    # [('Fourth', 4), ('first', 11), ('second', 2), ('third', 33)]

    dic_k_lst = {'11': [1, 2], 'ab': [3], 'cd': [0, -1, 2]}
    # Sort a dictionary by length of the value
    print sorted(dic_k_lst.items(), key=lambda item: len(item[1]))
    # [('ab', [3]), ('11', [1, 2]), ('cd', [0, -1, 2])]

    dic_k_set = {'11': {1, 2}, 'ab': {3}, 'cd': {0, -1, 2}}
    # Sort a dictionary by length of the value
    d_val_len = sorted(dic_k_set.items(), key=lambda item: len(item[1]))
    print d_val_len
    # [('ab', set([3])), ('11', set([1, 2])), ('cd', set([0, 2, -1]))]
    print d_val_len[0][1]
    # set([3])
    print len(d_val_len[0][1])
    # 1 (长度为 1)

对dict的value计数:

代码语言:javascript
复制
def dic_count_value():
    from collections import Counter
    dic_k_lst = {'11': None, 'ab': 3, 'name': 'xy', 'none': None, 'age': 26}
    print Counter(dic_k_lst.values())
    # Counter({None: 2, 'xy': 1, 26: 1, 3: 1})

    # 统计none与非none的数量
    count_none = 0
    count_not_none = 0
    for k in dic_k_lst.keys():
        if dic_k_lst[k] is None:
            count_none += 1
        else:
            count_not_none += 1

    print count_none, count_not_none
    # 2 3

统计dict中每个list的长度:

代码语言:javascript
复制
def count_val_lst_len():
    d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
    print map(len, d.values())
    # [4, 3]
    print sum(map(len, d.values()))
    # 7

dict value求和:

代码语言:javascript
复制
def sum_dic_val():
    d_info = {'33': 1, '88': 2, '22': 3, '44': 4}
    print sum(d_info.values())
    # 10
代码语言:javascript
复制
def dic_probability():
    p = {1: {1: 0.1, 2: 0.3}, 2: {1: 0.1, 2: 0.3}}
    # {1: {1: 0.1, 2: 0.3}, 2: {1: 0.1, 2: 0.3}}
    print p[2], p[2][2]
    # {1: 0.1, 2: 0.3} 0.3

具体见本人的github

参考:

https://stackoverflow.com/questions/613183/how-to-sort-a-dictionary-by-value

https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python

http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/

https://stackoverflow.com/questions/20464368/sort-a-dictionary-by-length-of-the-value

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年12月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档