我有一本这样的字典:
game =
{
"player": "Michael"
"round": 4,
"score": [
{
"1st": 342346,
"2nd": 345423,
},
{
"1st": 12411,
"2nd": 90296,
},
{
"1st": 20172,
"2nd": 21279,
},
{
"1st": 62348,
"2nd": 32662,
}
],
"player": "Sarah"
"round": 3,
"score": [
{
"1st": 6446,
"2nd": 5423,
},
{
"1st": 311,
"2nd": 1596,
},
{
"1st": 6472,
"2nd": 2119,
},
],
}
子弹不断更新。 我知道如何通过以下方式从这个dict中检索值:
game['score'][0]['1st']
game['score'][0]['2nd']
但我需要检索的总是最后一个,它不断更新取决于所玩的回合。 在本例中,最后一个是:
1st = 62348
2nd = 32662
如果lats on是基于'round'的值,请试试这个。。。
l = [ x for x in game['score'][game['round']-1].items()]
当您的字典有重复的键(这使它不正确)时,假设分数是正确的(列表),您可以使用负索引来获取末尾的项:
game['score'][-1]['1st']
game['score'][-1]['2nd']