Return first N key:value pairs from dict

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

    Did not see it on here. Will not be ordered but the simplest syntactically if you need to just take some elements from a dictionary.

    n = 2
    {key:value for key,value in d.items()[0:n]}
    
    0 讨论(0)
  • 2020-11-29 18:02

    For Python 3 and above,To select first n Pairs

    n=4
    firstNpairs = {k: Diction[k] for k in list(Diction.keys())[:n]}
    
    0 讨论(0)
  • 2020-11-29 18:04

    just add an answer using zip,

    {k: d[k] for k, _ in zip(d, range(n))}
    
    0 讨论(0)
  • 2020-11-29 18:04

    You can approach this a number of ways. If order is important you can do this:

    for key in sorted(d.keys()):
      item = d.pop(key)
    

    If order isn't a concern you can do this:

    for i in range(4):
      item = d.popitem()
    
    0 讨论(0)
  • 2020-11-29 18:05
    foo = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
    iterator = iter(foo.items())
    for i in range(3):
        print(next(iterator))
    

    Basically, turn the view (dict_items) into an iterator, and then iterate it with next().

    0 讨论(0)
  • 2020-11-29 18:06

    consider a dict

    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    
    from itertools import islice
    n = 3
    list(islice(d.items(),n))
    

    islice will do the trick :) hope it helps !

    0 讨论(0)
提交回复
热议问题