Return first N key:value pairs from dict

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

    There's no such thing a the "first n" keys because a dict doesn't remember which keys were inserted first.

    You can get any n key-value pairs though:

    n_items = take(n, d.iteritems())
    

    This uses the implementation of take from the itertools recipes:

    from itertools import islice
    
    def take(n, iterable):
        "Return first n items of the iterable as a list"
        return list(islice(iterable, n))
    

    See it working online: ideone


    Update for Python 3.6

    n_items = take(n, d.items())
    

提交回复
热议问题