对 Python 中的嵌套有序字典进行排序

Sorting nested ordered dictionary in Python

我的原始字典包含以下形式的值:

[(0, {'T8': (0.3978349, 0), 'T9': (0.84942997, 0), 'T6': (1.1480641, 0), 'T7': (2.1811862, 0), 'T4': (2.016099, 0), 'T5': (1.5923926, 0), 'T2': (0.20877934, 0), 'T3': (-0.095536113, 0), 'T1': (0.89533514, 0), 'T10': (0.11839861, 0)}), 
 (11, {'T14': (-0.50686657, 0), 'T15': (-0.47247946, 0), 'T16': (-1.4296696, 0), 'T17': (-0.62257302, 0), 'T12': (0.61257166, 0), 'T13': (0.64874935, 0), 'T21': (-0.46329427, 0), 'T20': (-0.72244251, 0), 'T18': (-0.85425723, 0), 'T19': (-1.4788039, 0)})
 (22, {'T25': (1.0260065, 0), 'T29': (2.1339068, 0), 'T28': (0.85323471, 0), 'T30': (2.4555078, 0), 'T23': (3.5931432, 0), 'T26': (0.52051008, 0), 'T32': (4.1754069, 0), 'T24': (1.2143329, 0), 'T27': (3.6651597, 0), 'T31': (3.1280968, 0)})]

这是 10k 相同行文件中的几行。最初因为这本字典是无序的,我通过删除前导 T 值使用键对其进行排序,现在它的排序形式为键

0 -> (values) 11-> (values) 22-> (values)

为了做到这一点,我做到了,

 nd = {}
 for qid, dinfo in res_scores.items():  #res_scores is the original unsorted dictionary
     val = int(re.sub("\D", "", qid))
     nd[val] = dinfo

 sd = OrderedDict(sorted(nd.items(), key=lambda t: t[0]))

现在显示的输出摘自 sd。现在我需要对 keys 的值进行排序,即:

{'T8': (0.3978349, 0), 'T9': (0.84942997, 0), 'T6': (1.1480641, 0), 'T7': (2.1811862, 0), 'T4': (2.016099, 0), 'T5': (1.5923926, 0), 'T2': (0.20877934, 0), 'T3': (-0.095536113, 0), 'T1': (0.89533514, 0), 'T10': (0.11839861, 0)}

通过删除前面的 T 值到此形式 ->

{1 : (0.89533514, 0), 2: (0.20877934, 0), 3: (-0.095536113, 0), 4: (2.016099, 0), 5: (1.5923926, 0), 6: (1.1480641, 0), 7: (2.1811862, 0), 8: (0.3978349, 0), 9: (0.84942997, 0), 10: (0.11839861, 0) }

我如何有效地处理 Python 中嵌套字典的值?我尝试了一些类似问题的解决方案,但未能解决问题。任何帮助将不胜感激。

根据我从你的问题中了解到的情况,你可以尝试像这样对你的 T 值进行排序:

T_values = {
    "T8": (0.3978349, 0),
    "T9": (0.84942997, 0),
    "T6": (1.1480641, 0),
    "T7": (2.1811862, 0),
    "T4": (2.016099, 0),
    "T5": (1.5923926, 0),
    "T2": (0.20877934, 0),
    "T3": (-0.095536113, 0),
    "T1": (0.89533514, 0),
    "T10": (0.11839861, 0),
}

result = {int(k[1:]): v for k, v in sorted(T_values.items(), key=lambda x: int(x[0][1:]))}

print(result)
# {1: (0.89533514, 0), 2: (0.20877934, 0), 3: (-0.095536113, 0), 4: (2.016099, 0), 5: (1.5923926, 0), 6: (1.1480641, 0), 7: (2.1811862, 0), 8: (0.3978349, 0), 9: (0.84942997, 0), 10: (0.11839861, 0)}

此外,如果您使用 Python3.6+,词典会保持插入顺序,因此您不需要 使用 OrderedDict

否则,您可以这样使用OrderedDict()

from collections import OrderedDict

OrderedDict((int(k[1:]), v) for k, v in sorted(T_values.items(), key=lambda x: int(x[0][1:])))
# OrderedDict([(1, (0.89533514, 0)), (2, (0.20877934, 0)), (3, (-0.095536113, 0)), (4, (2.016099, 0)), (5, (1.5923926, 0)), (6, (1.1480641, 0)), (7, (2.1811862, 0)), (8, (0.3978349, 0)), (9, (0.84942997, 0)), (10, (0.11839861, 0))])