python dict常用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haluoluo211/article/details/78806792

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

  1. list 转化为 dict

  2. dict遍历删除指定条件的元素

  3. dict安装key或者value排序

  4. dict的value统计计数


两个list转化为dict

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 的元素

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

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排序:

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计数:

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的长度:

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求和:

def sum_dic_val():
    d_info = {'33': 1, '88': 2, '22': 3, '44': 4}
    print sum(d_info.values())
    # 10
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

展开阅读全文

没有更多推荐了,返回首页