Return first N key:value pairs from dict

前端 未结 19 2175
花落未央
花落未央 2020-11-29 17:32

Consider the following dictionary, d:

d = {\'a\': 3, \'b\': 2, \'c\': 3, \'d\': 4, \'e\': 5}

I want to return the first N key:value pairs f

19条回答
  •  遥遥无期
    2020-11-29 18:08

    See PEP 0265 on sorting dictionaries. Then use the aforementioned iterable code.

    If you need more efficiency in the sorted key-value pairs. Use a different data structure. That is, one that maintains sorted order and the key-value associations.

    E.g.

    import bisect
    
    kvlist = [('a', 1), ('b', 2), ('c', 3), ('e', 5)]
    bisect.insort_left(kvlist, ('d', 4))
    
    print kvlist # [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    

提交回复
热议问题