从词典列表中删除项目并将其附加回去

时间:2019-05-07 06:55:52

标签: python list dictionary

假设我们有一个词典列表:

[{0: [0, 1, 2, 3], 1: [4]}, {2: [5, 6, 7, 8], 3: [9]}, {4: [10, 11, 12]}]

,我们希望根据一些元组(例如(0, 5, 10))来拆分此列表中的字典,以便对于元组中的每个ith值,如果该值存在于ith词典的任何最里面的子列表中,它都会被拆分进入自己的列表。另外,字典从0开始连续重新编号。因此上面的输出将是。

[{0:[0], 1: [1, 2, 3], 2: [4]}, {3:[5], 4: [6, 7, 8], 5: [9]}, {6:[10], 7: [11, 12]}]

由于0是第一个字典的一部分,它将被拆分。由于5是第二个字典的一部分,它将被拆分。同样,由于10是元组中的第3个值,并且它是第三个字典的一部分,因此将被拆分。

我写了以下代码:

for i in range(0, len(newlist)):
    for key, value in newlist[i].items():
        if x[i] in value:
            value.remove(x[i])
        newlist[i][key].append(x[i])

这会产生[{0: [1, 2, 3, 0], 1: [4, 0]}, {2: [6, 7, 8, 5], 3: [9, 5]}, {4: [11, 12, 10]}],它不是所需的输出,它会附加到密钥的每个列表中。

如何在所需输出中添加单个列表,以及如何使用列表理解或其他方式根据需要对列表重新编号?

2 个答案:

答案 0 :(得分:2)

我能够使用以下逻辑获得组合字典

li = [{0: [0, 1, 2, 3], 1: [4]}, {2: [5, 6, 7, 8], 3: [9]}, {4: [10, 11, 12]}]

values_list =  []
#Iterate through values of all dictionaries and join them end to end
for dct in li:
    values_list.extend(dct.values())

print(values_list)
#[[0, 1, 2, 3], [4], [5, 6, 7, 8], [9], [10, 11, 12]]
dct = {}
idx = 0

#Iterate through the list
for item in values_list:
    #If we have more then one item in the list, idx goes to first item, idx+1 goes to rest, idx gets incremented by 2
    if len(item) > 1:
        dct[idx] = [item[0]]
        dct[idx+1] = item[1:]
        idx+=2
    # If we have one item in the list, idx goes to first item, idx gets incremented by 1
    else:
        dct[idx] = [item[0]]
        idx+=1

print(dct)
#{0: [0], 1: [1, 2, 3], 2: [4], 3: [5], 4: [6, 7, 8], 5: [9], 6: [10], 7: [11, 12]}

答案 1 :(得分:2)

您可以使用统一索引idx来跟踪dict中的当前键号,并收集所有拆分的组件,然后将它们合并为新的dict
我已经编辑了您的示例输入,以显示更复杂的情况。

newlist = [{0: [0, 1, 2], 1: [3]}, {2: [4, 5, 6, 7, 8], 3: [9]}, {4: [10], 5:[11, 12]}]
x = [0, 5, 10]

for l in newlist:
    components = []
    for key, value in sorted(l.items()):  # sort items because the storage of dict is unordered
        for split_val in x:
            if split_val in value:  # split the list if in value
                index = value.index(split_val)
                components += [value[:index], [split_val], value[index + 1:]]
                break
        else:
            components.append(value)

    cur_dict = {}
    for component in components:
        if component:   # only add non-empty component
            cur_dict[idx] = component
            idx += 1
    result.append(cur_dict)

输出:

[{0: [0], 1: [1, 2], 2: [3]}, {3: [4], 4: [5], 5: [6, 7, 8], 6: [9]}, {7: [10], 8: [11, 12]}]
相关问题