我很难按价值排序字典

时间:2016-03-30 05:51:54

标签: python sorting dictionary

我知道这个话题还有其他问题;但是,我没有成功地将这些答案适用于我的代码。我需要帮助的是在我的第二和第三个打印函数中对字典进行排序,这些函数将按照打击顺序对字典进行排序,这是字典代码中的中间值,例如。 [' DH', 6 ,299]。我的代码如下:

def main():
    print('Rays Starters','\n')
    starters = {'DeJesus': ['DH', 6, 299],
                'Loney': ['1B', 4, 222],
                'Rivera': ['C', 9, 194],
                'Forythe': ['2B', 5, 304],
                'Souza Jr': ['RF', 2, 229],
                'Longoria': ['3B', 3, 282],
                'Cabrera': ['SS', 7, 214],
                'Kiermaier': ['CF', 1, 240],
                'Guyer': ['LF', 8, 275]}
for key, value in starters.items():
    print(key, value)
print('\n')

print("Today's lineup", '\n')
for key, value in (starters.items()):
    print('Batting {}: {} {}, current avg: {}'.format(value[1], value[0], key, value[2]))
print('\n')

print('Lineup change', '\n')
del starters['DeJesus']
del starters['Rivera']
starters2 = {'Wilson': ['C', 9, 152], 'Bechham': ['DH', 6, 200]}
starters.update(starters2)
for key, value in starters.items():
    print('Batting {}: {} {}, curent avg: {}'.format(value[1], value[0], key, value[2]))    

main()

作为参考,我当前的输出是:

Rays Starters 

Forythe ['2B', 5, 304]
Loney ['1B', 4, 222]
Longoria ['3B', 3, 282]
Kiermaier ['CF', 1, 240]
Guyer ['LF', 8, 275]
Rivera ['C', 9, 194]
DeJesus ['DH', 6, 299]
Cabrera ['SS', 7, 214]
Souza Jr ['RF', 2, 229]


Today's lineup 

Batting 5: 2B Forythe, curent avg: 304
Batting 4: 1B Loney, curent avg: 222
Batting 3: 3B Longoria, curent avg: 282
Batting 1: CF Kiermaier, curent avg: 240
Batting 8: LF Guyer, curent avg: 275
Batting 9: C Rivera, curent avg: 194
Batting 6: DH DeJesus, curent avg: 299
Batting 7: SS Cabrera, curent avg: 214
Batting 2: RF Souza Jr, curent avg: 229


Lineup change 

Batting 5: 2B Forythe, curent avg: 304
Batting 9: C Wilson, curent avg: 152
Batting 4: 1B Loney, curent avg: 222
Batting 3: 3B Longoria, curent avg: 282
Batting 1: CF Kiermaier, curent avg: 240
Batting 8: LF Guyer, curent avg: 275
Batting 6: DH Bechham, curent avg: 200
Batting 7: SS Cabrera, curent avg: 214
Batting 2: RF Souza Jr, curent avg: 229

1 个答案:

答案 0 :(得分:4)

sorted()接受一个参数key,这是一个返回要排序的值的函数。

试试这个:

def key_func(item):
    value = item[1]
    order = value[1]
    return order
for key, value in sorted(starters.items(), key=key_func):
    ...

或者更简单:

for key, value in sorted(starters.items(), key=lambda x: x[1][1]):
    ...