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

2024-03-29 06:46:57 发布

您现在位置: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,
        },
    ],
}

轮次不断更新的地方。我知道如何使用以下命令从该命令中检索值:

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

但我需要总是检索最后一个,它会根据所玩的回合不断更新。 在这种情况下,最后一个是:

1st = 62348
2nd = 32662

Tags: 命令game字典地方情况scoreplayerround
2条回答

如果lats on基于“round”的值,请尝试此

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

虽然您的词典有重复的键(这使得它不正确),但假设分数正确(列表),您可以使用负索引来获取末尾的项:

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

相关问题 更多 >