将具有重复键的字典中的键和值对添加到字典中

时间:2020-02-13 17:46:10

标签: python-3.x

results是列表中包含数据的列表,如结果部分所示。我希望在字典中实现字典,如结果部分所示。

输入:

results = [['abc','12'3,'1123','qwe', 'asd'],['abc','123,'1123','qwe', '123'],['abc','123','1123','ewq','zxc'], ['bcd','123','1123','ewq','zxc'], ['bcd','123','1123','ewq','zxc]]

代码:

report_dict = dict()
axis_list = []
results = self.report_data(conn)
for row in results:
  try:
    report_dict[row[0]] = {}
    report_dict[row[0]][row[3]] = row[1]
  except IndexError:
    None 
  print(report_dict)

结果:

report_dict = { 'abc': {'qwe':['asd','123'], 'ewq':['zxc']}, 'bcd' : {'qwe':['asd'], 'ewq':['zxc']} …..}

请注意,数据集中有重复的键。

2 个答案:

答案 0 :(得分:1)

以下是您在列表中有元组的直接问题的解决方案:

from collections import defaultdict
report_dict = defaultdict(list)
# results = self.report_data(conn)
results = [["abc",123,1123,"qwe", "asd"],["abc",123,1123,"ewq","zxc"], ["bcd",123,1123,"ewq","zxc"], ["bcd",123,1123,"ewq","zxc"]]
for row in results:
    try:
        report_dict[row[0]].append((row[3], row[1]))
    except IndexError:
        None 
print(report_dict)

结果:defaultdict(<class 'list'>, {'abc': [('qwe', 123), ('ewq', 123)], 'bcd': [('ewq', 123), ('ewq', 123)]})

您还可以使用以下行将其更改为列表中的词典

        report_dict[row[0]].append({row[3]: row[1]})

结果:defaultdict(<class 'list'>, {'abc': [{'qwe': 123}, {'ewq': 123}], 'bcd': [{'ewq': 123}, {'ewq': 123}]})

答案 1 :(得分:1)

您可以这样做:

d = {}
for i in results:
   if not d.get(i[0],0):
      d[i[0]] = {}
   if not d[i[0]].get(i[3],0):
      d[i[0]][i[3]] = []
   d[i[0]][i[3]].append(i[4])
d
{'abc': {'qwe': ['asd', '123'], 'ewq': ['zxc']}, 'bcd': {'ewq': ['zxc', 'zxc']}}