Return first N key:value pairs from dict

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

    For Python 3.8 the correct answer should be:

    import more_itertools
    
    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    
    first_n = more_itertools.take(3, d.items())
    print(len(first_n))
    print(first_n)
    

    Whose output is:

    3
    [('a', 3), ('b', 2), ('c', 3)]
    

    After pip install more-itertools of course.

提交回复
热议问题