如何在python中对字典中的列表进行排序?

时间:2019-01-30 11:23:48

标签: python sorting dictionary

我有以下以json格式表示数据的字典:

{'0': {'related_items': [6, 7],
  'values': [0.8111071056538126, 0.8660254037844388]},
 '1': {'related_items': [5, 8],
  'values': [0.9999999999999998, 0.7071067811865475]},
 '222': {'related_items': [], 'values': []},
 '33': {'related_items': [], 'values': []},
 '44': {'related_items': [99], 'values': [0.7071067811865475]},
 '5': {'related_items': [1, 8],
  'values': [0.9999999999999998, 0.7071067811865475]},
 '6': {'related_items': [0, 7, 99],
  'values': [0.8111071056538126, 0.936585811581694, 0.8111071056538126]},
 '7': {'related_items': [0, 6, 99],
  'values': [0.8660254037844388, 0.936585811581694, 0.8660254037844388]},
 '8': {'related_items': [1, 5],
  'values': [0.7071067811865475, 0.7071067811865475]},
 '99': {'related_items': [44, 6, 7],
  'values': [0.7071067811865475, 0.8111071056538126, 0.8660254037844388]}}

我想根据related_items列表的顺序对values列表进行排序(递减): 例如,对于项目“ 0”,列表将按以下顺序排序: {'0':{'related_items':[7,6],   '值':[0.8660254037844388,0.8111071056538126]} ...

for i, j in json_data.items():
    r = j['related_items']
    s = j['values']
    if r:
        sim_final, rel_final = (list(t) for t in zip(*sorted(zip(s, r),reverse=True)))
        json_data[i]['values']=sim_final
        json_data[i]['related_items']=rel_final

预期输出:

{'0': {'related_items': [7, 6],
  'values': [0.8660254037844388, 0.8111071056538126]},
 '1': {'related_items': [5, 8],
  'values': [0.9999999999999998, 0.7071067811865475]},
 '222': {'related_items': [], 'values': []},
 '33': {'related_items': [], 'values': []},
 '44': {'related_items': [99], 'values': [0.7071067811865475]},
 '5': {'related_items': [1, 8],
  'values': [0.9999999999999998, 0.7071067811865475]},
 '6': {'related_items': [7, 99, 0],
  'values': [0.936585811581694, 0.8111071056538126, 0.8111071056538126]},
 '7': {'related_items': [6, 99, 0],
  'values': [0.936585811581694, 0.8660254037844388, 0.8660254037844388]},
 '8': {'related_items': [5, 1],
  'values': [0.7071067811865475, 0.7071067811865475]},
 '99': {'related_items': [7, 6, 44],
  'values': [0.8660254037844388, 0.8111071056538126, 0.7071067811865475]}}

我的实际字典非常大。如何简化以上代码中的for循环?

1 个答案:

答案 0 :(得分:0)

for k, v in json_data.items():
    x = v["related_items"]
    x.sort(reverse=True)
    y = []
    for i in x:
        y.append(v["values"][v["related_items"].index(i)])
    v["related_items"] = x
    v["values"] = y

不知道它是否更优雅,但是它是我会怎么做的。