Python 如何一次迭代字典-n个键值对
我有一本很大的字典,里面有成千上万的元素。我需要用这个字典作为参数执行一个函数。现在,我不想在一次执行中传递整个字典,而是希望成批执行函数——每次使用字典的x个键值对 我正在做以下工作:Python 如何一次迭代字典-n个键值对,python,dictionary,Python,Dictionary,我有一本很大的字典,里面有成千上万的元素。我需要用这个字典作为参数执行一个函数。现在,我不想在一次执行中传递整个字典,而是希望成批执行函数——每次使用字典的x个键值对 我正在做以下工作: mydict = ##some large hash x = ##batch size def some_func(data): ##do something on data temp = {} for key,value in mydict.iteritems(): if len(te
mydict = ##some large hash
x = ##batch size
def some_func(data):
##do something on data
temp = {}
for key,value in mydict.iteritems():
if len(temp) != 0 and len(temp)%x == 0:
some_func(temp)
temp = {}
temp[key] = value
else:
temp[key] = value
if temp != {}:
some_func(temp)
对我来说,这看起来很粗糙。我想知道是否有一种优雅/更好的方法可以做到这一点。我经常使用这个小工具:
import itertools
def chunked(it, size):
it = iter(it)
while True:
p = tuple(itertools.islice(it, size))
if not p:
break
yield p
对于您的用例:
for chunk in chunked(big_dict.iteritems(), batch_size):
func(chunk)
以下是根据我先前的回答改编的两个解决方案 或者,您可以从字典中获取
项的列表
,并从该列表的片段中创建新的dict
s。不过,这并不是最优的,因为它需要大量复制那本巨大的词典
def chunks(dictionary, size):
items = dictionary.items()
return (dict(items[i:i+size]) for i in range(0, len(items), size))
或者,您可以使用一些itertools
模块的函数在循环时生成新的子字典。这与@georg的答案类似,只是使用了一个for
循环
from itertools import chain, islice
def chunks(dictionary, size):
iterator = dictionary.iteritems()
for first in iterator:
yield dict(chain([first], islice(iterator, size - 1)))
示例用法。对于这两种情况:
mydict = {i+1: chr(i+65) for i in range(26)}
for sub_d in chunks2(mydict, 10):
some_func(sub_d)
发件人:
你可以试试,或者你好,乔治。谢谢你的回答。请解释一下
chunked
方法的性能。比我共享的解决方案更有效吗?@nish:我想应该是有效的itertools
是用C编写的,比python快得多。在Python3中,它将是big\u dict.items()而不是big\u dict.iteritems()
def chunked(iterable, n):
"""Break an iterable into lists of a given length::
>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of ``iterable`` is not evenly divisible by ``n``, the last
returned list will be shorter.
This is useful for splitting up a computation on a large number of keys
into batches, to be pickled and sent off to worker processes. One example
is operations on rows in MySQL, which does not implement server-side
cursors properly and would otherwise load the entire dataset into RAM on
the client.
"""
# Doesn't seem to run into any number-of-args limits.
for group in (list(g) for g in izip_longest(*[iter(iterable)] * n,
fillvalue=_marker)):
if group[-1] is _marker:
# If this is the last group, shuck off the padding:
del group[group.index(_marker):]
yield group