从 dict 返回前 N 个键:值对 [英] Return first N key:value pairs from dict
本文介绍了从 dict 返回前 N 个键:值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下字典,d:
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
我想从 d 返回前 N 个键:值对(在这种情况下 N <= 4).这样做的最有效方法是什么?
解决方案
没有前 n"个键这样的东西,因为 dict
不记得哪个键是最先插入的.>
你可以得到任何n个键值对:
n_items = take(n, d.iteritems())
这使用了 中的
食谱:take
实现itertools
from itertools import islicedef take(n, iterable):将可迭代对象的前 n 个项目作为列表返回"返回列表(islice(可迭代,n))
在线查看:ideone
Python 3.6 更新
n_items = take(n, d.items())
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 from d (N <= 4 in this case). What is the most efficient method of doing this?
解决方案
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())
这篇关于从 dict 返回前 N 个键:值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文