我尝试使用嵌套字典创建字典。我正在使用的所有值来自3个不同的列表(相同的长度)。
最终结果如下:
d = {SP1: {TS1:[values here], TS2:[values here]}, SP2:{TS1:[other values]}}
我面临的主要问题是应该过滤列表,因为它们有重复的值:
# this should be the first key of the dictionary (SP1, SP2..), not repeated
sp = [2, 3, 4, 5, 7, 9, 9, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 2, 3, 4, 5, 7, 9, 9, 12, 14, 15]
# this it the first inner key (TS1, TS2..), not repeated but coherent to the sp list values
ts = [2, 3, 3, 3, 2, 1, 3, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 1, 3, 1, 1, 3]
# these values should go inside the list of each TS key
sim = [14.4953689575, 14.2694330215, 14.3503818512, 14.2953929901, 14.1140880585, 13.9398431778, 13.8227128983, 13.9122915268, 13.8505115509, 14.3296766281, 15.0080194473, 14.7962331772, 14.3174362183, 14.0135688782, 13.8948440552, 13.8888025284, 13.7929182053, 13.7562999725, 13.7984809875, 14.4026594162, 14.8861970901, 14.7377538681, 14.853559494, 14.7751989365, 14.603521347, 14.4809532166, 14.4053077698, 14.5300836563, 14.4450139999, 14.8226003647]
我尝试过类似的东西:
d = {}
for i, j in enumerate(sp):
d[j] = {}
for i in ts:
if ts[i] not in d[j]:
d[j] = {ts[i] : []}
d[j][ts[i]].append(sim[i])
但是输出错误,因为它仅从最后一个创建了TS
个密钥和sim
值。
这是预期的最终字典:
d = {
2: {2: [14.4953689575, 14.8861970901]},
3: {3: [14.2694330215, 14.7377538681]},
4: {3: [14.3503818512, 14.853559494]},
5: {3: [14.2953929901, 14.7751989365]},
7: {2: [14.1140880585, 14.603521347]},
9: {1: [13.9398431778, 14.4809532166], 3: [13.8227128983, 14.4053077698]},
12: {1: [13.9122915268, 14.5300836563]},
14: {1: [13.8505115509, 14.4450139999]},
15: {3: [14.3296766281, 14.8226003647]},
16: {2: [15.0080194473]},
17: {1: [14.7962331772]},
18: {1: [14.3174362183]},
19: {1: [14.0135688782]},
20: {1: [13.8948440552]},
21: {1: [13.8888025284]},
22: {1: [13.7929182053]},
23: {2: [13.7562999725]},
24: {2: [13.7984809875]},
25: {2: [14.4026594162]}
}
感谢任何提示
答案 0 :(得分:1)
inner_dicts = [{k: [v]} for k, v in zip(ts, sim)]
result = {}
for key, value in zip(sp, inner_dicts):
result[key] = result.get(key, {})
for inner_k, inner_v in value.items():
result[key][inner_k] = list(set(result[key].get(inner_k, []) + inner_v))