Return first N key:value pairs from dict

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

    Were d is your dictionary and n is the printing number:

    for idx, (k, v) in enumerate(d):
      if idx == n: break
      print((k, v))
    

    Casting your dictionary to list can be slow. Your dictionary may be too large and you don't need to cast all of it just for printing a few of the first.

提交回复
热议问题