我有一本字典:
sequence = {
'group4': {'shutdown_grace': 300, 'startup_order': 4, 'warmup_time': 300, 'shutdown_order': 6, 'servers': ['group4_1', 'group4_2']},
'group1': {'shutdown_grace': 300, 'startup_order': 1, 'warmup_time': 900, 'shutdown_order': 10, 'servers': ['group1_1', 'group1_2', 'group1_3']},
'group3': {'shutdown_grace': 300, 'startup_order': 3, 'warmup_time': 900, 'shutdown_order': 7, 'servers': ['group3_1', 'group3_2']},
'group2': {'shutdown_grace': 300, 'startup_order': 2, 'warmup_time': 900, 'shutdown_order': 8, 'servers': ['group2_1', 'group2_2']}
}
我想创建一个循环,使用sequence
字典中的值(例如sequence['group4']['startup_order']
)来浏览此列表。如何使用sorted()
?
我试过用这个:
for k, v in sorted(sequence.items(), key=sequence[k]['startup_order']):
print(k, v)
但它引发了错误:UnboundLocalError: local variable 'k' referenced before assignment
答案 0 :(得分:4)
for k, v in sorted(sequence.items(), key=lambda x: x[1]['startup_order']):
print(k, v)
sequence = {
'group4': {'shutdown_grace': 300, 'startup_order': 4,
'warmup_time': 300, 'shutdown_order': 6,
'servers': ['group4_1', 'group4_2']},
'group1': {'shutdown_grace': 300, 'startup_order': 1,
'warmup_time': 900, 'shutdown_order': 10,
'servers': ['group1_1', 'group1_2', 'group1_3']},
'group3': {'shutdown_grace': 300, 'startup_order': 3,
'warmup_time': 900, 'shutdown_order': 7,
'servers': ['group3_1', 'group3_2']},
'group2': {'shutdown_grace': 300, 'startup_order': 2,
'warmup_time': 900, 'shutdown_order': 8,
'servers': ['group2_1', 'group2_2']}
}
for k, v in sorted(sequence.items(), key=lambda x: x[1]['startup_order']):
print(k, v)
('group1', {'servers': ['group1_1', 'group1_2', 'group1_3'], 'shutdown_grace': 300, 'startup_order': 1, 'shutdown_order': 10, 'warmup_time': 900})
('group2', {'servers': ['group2_1', 'group2_2'], 'shutdown_grace': 300, 'startup_order': 2, 'shutdown_order': 8, 'warmup_time': 900})
('group3', {'servers': ['group3_1', 'group3_2'], 'shutdown_grace': 300, 'startup_order': 3, 'shutdown_order': 7, 'warmup_time': 900})
('group4', {'servers': ['group4_1', 'group4_2'], 'shutdown_grace': 300, 'startup_order': 4, 'shutdown_order': 6, 'warmup_time': 300})
答案 1 :(得分:1)
您可以使用Sorted()
,然后将其转换为Ordered dict:
import collections
data=collections.OrderedDict(sorted(sequence.items(),key=lambda x:x[1]['shutdown_order']))
现在数据是一个字典,你可以像普通字典一样迭代:
for i,j in data.items():
print(i,j)
输出:
group4 {'shutdown_grace': 300, 'warmup_time': 300, 'startup_order': 4, 'servers': ['group4_1', 'group4_2'], 'shutdown_order': 6}
group2 {'shutdown_grace': 300, 'warmup_time': 900, 'startup_order': 2, 'servers': ['group2_1', 'group2_2'], 'shutdown_order': 8}
group1 {'shutdown_grace': 300, 'warmup_time': 900, 'startup_order': 1, 'servers': ['group1_1', 'group1_2', 'group1_3'], 'shutdown_order': 10}
group3 {'shutdown_grace': 300, 'warmup_time': 900, 'startup_order': 3, 'servers': ['group3_1', 'group3_2'], 'shutdown_order': 70}