python - 如何遍历字典——一次 n 个键值对

标签 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(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)

关于python - 如何遍历字典——一次 n 个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28022223/

相关文章:

database - 如何使用 sed 使用引用文件在文件中进行数千次替换?

c# - MongoDB 序列化 Dictionary<MyEnum,object>

python - 对 C 的标注可以预估 Python 字典的容量吗?

python - 使用类作为装饰器时,为什么 'self' 不在 args 中?

python - 查找较小数组与较大数组最匹配的位置

python - Pandas :从列 A 中提取 B 列不存在的数据

ios - swift 中字典键的数组

python - 将字典的值及其计数转换为另一个字典

python - 正则表达式捕获时打印出子进程

python - Python中分组数据的累积自定义函数