python 如何连接具有相同键的字典的值

wwwo4jvm  于 2023-09-29  发布在  Python
关注(0)|答案(5)|浏览(77)

我有一个字典,其中包含一些字典(其数量是不固定的),而这些字典又包含数字列表(每个子字典的列表数量也是不固定的)。

Data_Dict ={0:{0:[list 00], 1:[list 01], 2:[list 02], 3:[list 03], ...},
            1:{0:[list 10], 1:[list 11], 2:[list 12], 3:[list 13], ...},
            2:{0:[list 20], 1:[list 21], 2:[list 22], 3:[list 23], ...},
            ...}

Data_Dict是我从不同文件中解析数据得到的,每个文件都提供了关于不同对象的信息。
字典的键来自我用来导入不同文件或不同对象的for循环(更具体地说,当值是字典时,键引用文件,而当值是字符串时,键引用单个对象)。
我试图做的是将所有子字典的列表与一个特定的键连接在一个列表中。保持顺序是很重要的,这意味着列表Data_Dict[0][0]的元素必须在列表Data_Dict[1][0]的元素之前,依此类推。在这里,你有想要的结果:

NewData_Dict ={0:[list 00, list 10, list 20,...],
               1:[list 01, list 11, list 21,...],
               2:[list 02, list 12, list 22,...], 
               ...}

我一直在尝试使用另一个问题(How can I combine dictionaries with the same keys?)中的建议,即:

NewData_Dict = {}
for k in Data_Dict[0]:
    NewData_Dict[k] = [d[k] for d in Data_Dict]

它给我的是:

NewData_Dict[k] = [d[k] for d in Data_Dict]
TypeError: 'int' object is not subscriptable

我也试着回答问题Combine values of same keys in a list of dicts

NewData_Dict = {
    k: [d.get(k) for d in Data_Dict]
    for k in set().union(*Data_Dict)
}

得到回报:

NewData_Dict = {k: [d.get(k) for d in Data_Dict] for k in set().union(*Data_Dict)}
TypeError: 'int' object is not iterable

我想问题可能是我的字典的键是“int”。我的假设正确吗?我该怎么办?

ncgqoxb0

ncgqoxb01#

代码注解中的解释。试试看:

Data_Dict ={0:{0:["A", "B", "C"], 1:["E", "F", "G"], 2:["H", "I", "J"], 3:["K", "L", "M"]},
            1:{0:["N", "O", "P"], 1:["Q", "R", "S"], 2:["T", "U", "V"], 3:["W", "X", "Y"]},
            2:{0:["AA", "BB", "CC"], 1:["DD","EE","FF"], 2:["GG", "HH", "II"], 3:["JJ","KK","LL"]},}

New_Data_Dict = {}
# for each key in Data_Dict
for dict in Data_Dict:
    # for each key in Data_Dict[key]
    for list in Data_Dict[dict]:
        # if list key exists in New_Data_Dict append Data_Dict[dict key][list key] <<== Value of list
        if list in New_Data_Dict:
            New_Data_Dict[list]+=(Data_Dict[dict][list])
        # else create list key and add value
        else:
            New_Data_Dict[list] = Data_Dict[dict][list]

print(New_Data_Dict)

输出量:

{0: ['A', 'B', 'C', 'N', 'O', 'P', 'AA', 'BB', 'CC'], 
 1: ['E', 'F', 'G', 'Q', 'R', 'S', 'DD', 'EE', 'FF'], 
 2: ['H', 'I', 'J', 'T', 'U', 'V', 'GG', 'HH', 'II'], 
 3: ['K', 'L', 'M', 'W', 'X', 'Y', 'JJ', 'KK', 'LL']}
u5rb5r59

u5rb5r592#

简单的解决方案在这里

dictionaries = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'c': 6}]

result = {}

for dictionary in dictionaries:
    for key, value in dictionary.items():
        if key in result:
            result[key].append(value)
        else:
            result[key] = [value]

print(result)
zour9fqk

zour9fqk3#

这个循环可能会有帮助

the_new_dic = {}
for key_1 in range(len(the_dict)):
  for key_2 in range(len(the_dict[key_1])):
    the_new_dic[key_1].extend(the_dict[key_2][key_1])
hvvq6cgz

hvvq6cgz4#

您可以遍历每个嵌套dict的项。

data = {0: {0: ['00', '00'], 1: ['01', '01'], 2: ['02', '02'], 3: ['03', '03']},
        1: {0: ['10', '10'], 1: ['11', '11'], 2: ['12', '12'], 3: ['13', '13']},
        2: {0: ['20', '20'], 1: ['21', '21'], 2: ['22', '22'], 3: ['23', '23']}}

new = {}
for x in data.values():
    for key in x:
        try:
            new[key].extend(x[key])
        except KeyError:
            new[key] = x[key]

输出量:

>>> new
{0: ['00', '00', '10', '10', '20', '20'], 
 1: ['01', '01', '11', '11', '21', '21'], 
 2: ['02', '02', '12', '12', '22', '22'], 
 3: ['03', '03', '13', '13', '23', '23']}
odopli94

odopli945#

for i in range(len(Data_dict)):
    for j in range(len(Data_dict[i] - 1):
        Data_dict[i][0].extend(Data_dict[i][j+1]

相关问题