[英]Iterating over first half a dictionary in python
How to iterate over first half of dictionary in python 如何在python中迭代字典的前半部分
This iterates over all values in the dictionary 这会遍历字典中的所有值
for key, value in checkbox_dict.iteritems():
print key,value
But I want to iterate over the first half of the dictionary only. 但是我只想遍历字典的前半部分。
one way is to do it like this 一种方法是这样做
for key, value in dict(checkbox_dict.items()[:11]).iteritems():
print key,value
Is there any better way also ? 还有更好的办法吗?
If you mean: over half of the items here's a way: 如果您的意思是:一半以上的项目是一种方法:
for key, value in checkbox_dict.items()[:int(len(checkbox_dict)/2)]:
pass
… But be aware: the elements in a normal dictionary don't necessarily keep the same iteration order that was used for inserting the elements … unless you use an OrderedDict
. …但是要注意:普通字典中的元素不一定要保持与插入元素相同的迭代顺序…除非您使用
OrderedDict
。
You can use itertools.islice
to slice the dict.iteritems
iterator, unlike dict.items()
with slice this won't create an intermediate list in memory. 您可以使用
itertools.islice
对dict.iteritems
迭代器进行切片,这与dict.items()
与slice不同,这不会在内存中创建中间列表。
>>> from itertools import islice
>>> d = dict.fromkeys('abcdefgh')
>>> for k, v in islice(d.iteritems(), len(d)/2):
print k, v
...
a None
c None
b None
e None
Note that normal dictionaries are unordered, so the items are returned in arbitrary order. 请注意,普通字典是无序的,因此项目将以任意顺序返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.