Return first N key:value pairs from dict

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

    This might not be very elegant, but works for me:

    d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    
    x= 0
    for key, val in d.items():
        if x == 2:
            break
        else:
            x += 1
            # Do something with the first two key-value pairs
    

提交回复
热议问题