Return first N key:value pairs from dict

前端 未结 19 2217
花落未央
花落未央 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条回答
  •  萌比男神i
    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)]
    

提交回复
热议问题