提问者:小点点

Python检索不断更新的嵌套字典中的最后一个键[关闭]


我有一本这样的字典:

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

共2个答案

匿名用户

如果lats on是基于'round'的值,请试试这个。。。

l = [ x for x in game['score'][game['round']-1].items()]

匿名用户

当您的字典有重复的键(这使它不正确)时,假设分数是正确的(列表),您可以使用负索引来获取末尾的项:

game['score'][-1]['1st']
game['score'][-1]['2nd']