Return first N key:value pairs from dict

前端 未结 19 2015
花落未央
花落未央 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:27

    Dictionary maintains no order , so before picking top N key value pairs lets make it sorted.

    import operator
    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
    d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
    #itemgetter(0)=sort by keys, itemgetter(1)=sort by values
    

    Now we can do the retrieval of top 'N' elements:, using the method structure like this:

    def return_top(elements,dictionary_element):
        '''Takes the dictionary and the 'N' elements needed in return
        '''
        topers={}
        for h,i in enumerate(dictionary_element):
            if h<elements:
                topers.update({i:dictionary_element[i]})
        return topers
    

    to get the top 2 elements then simply use this structure:

    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
    d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
    d=return_top(2,d)
    print(d)
    
    0 讨论(0)
提交回复
热议问题