Return first N key:value pairs from dict

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

    in py3, this will do the trick

    {A:N for (A,N) in [x for x in d.items()][:4]}
    

    {'a': 3, 'b': 2, 'c': 3, 'd': 4}

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2020-11-29 18:11

    I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.

    I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.

    Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.

    The answer to the OP question that worked best for me.

    itr = iter(dic.items())
    lst = [next(itr) for i in range(3)]
    
    0 讨论(0)
  • 2020-11-29 18:12

    A very efficient way to retrieve anything is to combine list or dictionary comprehensions with slicing. If you don't need to order the items (you just want n random pairs), you can use a dictionary comprehension like this:

    # Python 2
    first2pairs = {k: mydict[k] for k in mydict.keys()[:2]}
    # Python 3
    first2pairs = {k: mydict[k] for k in list(mydict)[:2]}
    

    Generally a comprehension like this is always faster to run than the equivalent "for x in y" loop. Also, by using .keys() to make a list of the dictionary keys and slicing that list you avoid 'touching' any unnecessary keys when you build the new dictionary.

    If you don't need the keys (only the values) you can use a list comprehension:

    first2vals = [v for v in mydict.values()[:2]]
    

    If you need the values sorted based on their keys, it's not much more trouble:

    first2vals = [mydict[k] for k in sorted(mydict.keys())[:2]]
    

    or if you need the keys as well:

    first2pairs = {k: mydict[k] for k in sorted(mydict.keys())[:2]}
    
    0 讨论(0)
  • 2020-11-29 18:14

    To get the top N elements from your python dictionary one can use the following line of code:

    list(dictionaryName.items())[:N]
    

    In your case you can change it to:

    list(d.items())[:4]
    
    0 讨论(0)
  • 2020-11-29 18:14

    This might not be very elegant, but works for me:

    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    
    x= 0
    for key, val in d.items():
        if x == 2:
            break
        else:
            x += 1
            # Do something with the first two key-value pairs
    
    0 讨论(0)
提交回复
热议问题