这是一种方法,使用生成器产生连续的键值对:
data = {"A":[1,2,3,4,5],"B":[1,3],"C":[1,5,6,7,8]}
def key_value_gen(data):
# will yield ('A',1),('A',2),.... ('C',8)
for key,values in data.items():
for value in values:
yield key,value
out = []
size = 4
for index,(key,value) in enumerate(key_value_gen(data)):
# if the index is a multiple of size,we add a new dict
if index % size == 0:
out.append({})
out[-1].setdefault(key,[]).append(value)
print(out)
# [{'A': [1,4]},{'A': [5],'B': [1,3]},{'C': [1,{'C': [5,8]}]
,
另一种只是迭代方法的方法:
def group_by_count(dic,size):
output,temp,count = [],{},0
for k,v in dic.items():
for x in v:
if count == size:
output.append(temp)
temp,count = {},0
temp[k] = temp.get(k,[]) + [x]
count += 1
if temp:
output.append(temp)
return output
d = {"A":[1,8]}
output = group_by_count(d,4)
for dic in output:
print(dic)
输出:
{'A': [1,4]}
{'A': [5],3]}
{'C': [1,4]}
{'C': [5,8]}
本文链接:https://www.f2er.com/3170144.html