如何根据列表的长度将包含列表的字典拆分为相等的部分

比方说,我有一个字典,其中包含多个大小不同的列表,如何根据列表的长度将字典分为4个等长的字典。有没有简单的方法可以做到这一点?

dict = {"A":[1,2,3,4,5],"B":[1,3],"C":[1,5,6,7,8]}

我如何将其分成相同长度的4个字典,以便得到以下结果:

dict1 = {"A":[1,4]}
dict2 = {"A":[5],3]}
dict3 = {"C":[1,4]}
dict4 = {"C":[5,8]}

编辑:如果无法平均分配,那么其中一个字典的长度会比其他字典稍长。

t456456 回答:如何根据列表的长度将包含列表的字典拆分为相等的部分

这是一种方法,使用生成器产生连续的键值对:

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

大家都在问