美文网首页
2018-04-23 python dict的排序

2018-04-23 python dict的排序

作者: mugtmag | 来源:发表于2018-04-23 15:51 被阅读38次
  1. 对一个dictionary利用value排序:
prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
d = sorted(prices, key=lambda k: prices[k], reverse=True)
>>> d   # 得到的是按照values排序得到的keys
['AAPL', 'IBM', 'ACME', 'HPQ', 'FB'] 

min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')
  1. 对list of dicts 利用dict中相同的key对应的value排序
d = [{"num":2}, {"num":1}, {"num":3}]
d_ = sorted(d, key=lambda k: k['num'])
>>> d_
[{'num': 1}, {'num': 2}, {'num': 3}]

  1. 对list of dicts 利用dict中的key排序
d = [{2:"w"}, {1:"r"}, {3:"e"}]
d_ = sorted(d, key=lambda k: list(k.keys())[0])
>>> d_
[{1: 'r'}, {2: 'w'}, {3: 'e'}]
  1. 对list of dicts 利用另外一个dict排序
sort_by_ = ['北京', '上海', '西安', '郑州']
rsp_data = [{'city': '西安', 'num': 2}, {'city': '上海', 'num': 1}, {'city': '北京', 'num': 3},{'city': '郑州', 'num': 4}]
rsp_data = sorted(rsp_data, key=lambda k: sort_by_.index(k['city']))
>>> rsp_data
[{'city': '北京', 'num': 3}, {'city': '上海', 'num': 1}, {'city': '西安', 'num': 2}, {'city': '郑州', 'num': 4}]

  1. 对 dict 利用 另外一个dict排序
dict_to_sort = {'c': 123, 'b': 'test', 'a': '-'}
dict_key = {'a': 1, 'b': 3, 'c': 2}  # The order should be "a c b"
# sort dict_to_sort by using dict_key
sorted_pair_list = sorted(dict_to_sort.items(), key=lambda x: dict_key.get(x[0]))
>>> sorted_pair_list
[('a', '-'), ('c', 123), ('b', 'test')]
  1. 利用第三方库heapq对list 和 list of dicts 排序:
    (1). 参考:python3-cookbook

相关文章

  • python 常用操作记录

    python 列表及字典(按key、按value排序) python dict按照key 排序:1、method ...

  • 2018-04-23 python dict的排序

    对一个dictionary利用value排序: 对list of dicts 利用dict中相同的key对应的va...

  • 2022-02-16

    python如何对一个dict list 根据field 排序

  • python dict排序

    下面的是按照value的值从大到小的顺序来排序。 输出的结果:[('aa', 74), ('a', 31), ('...

  • Python dict排序

    sorted 函数按key值对字典排序 sorted 函数按value值对字典排序 字典列表排序

  • 12.4、python内置函数—sorted

    内置函数——sorted 对List、Dict进行排序,Python提供了两个方法 对给定的List L进行排序,...

  • python dict字典排序

    Python的sorted函数可以对字典的key排序,可以对字典的value排序。 1.sorted函数对字典的k...

  • 如何对python中的字典排序?

    根据dict的值排序 根据dict的key排序 通过列表中的字典的某个值对列表进行排序

  • Python基础入门—字典(dict)

    概述:python中的dict具有如下特点 dict是可变的 dict可以存储任意数量的Python对象 dict...

  • 字典排序

    原型函数:sorted(dict,value,reverse) dict:dict为比较函数 value:为排序对...

网友评论

      本文标题:2018-04-23 python dict的排序

      本文链接:https://www.haomeiwen.com/subject/aixllftx.html