Return first N key:value pairs from dict

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

    Python's dicts are not ordered, so it's meaningless to ask for the "first N" keys.

    The collections.OrderedDict class is available if that's what you need. You could efficiently get its first four elements as

    import itertools
    import collections
    
    d = collections.OrderedDict((('foo', 'bar'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')))
    x = itertools.islice(d.items(), 0, 4)
    
    for key, value in x:
        print key, value
    

    itertools.islice allows you to lazily take a slice of elements from any iterator. If you want the result to be reusable you'd need to convert it to a list or something, like so:

    x = list(itertools.islice(d.items(), 0, 4))
    

提交回复
热议问题