代码之家  ›  专栏  ›  技术社区  ›  matteo

循环嵌套字典python中的混淆

  •  0
  • matteo  · 技术社区  · 8 年前

    我正在尝试使用嵌套字典创建字典。我正在使用的所有值都来自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])
    

    但是输出是错误的,因为它正在创建bot 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]}
    }
    

    1 回复  |  直到 8 年前
        1
  •  1
  •   Yaroslav Surzhikov    8 年前
    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))