字典理解值是列表

Dictionary Comprehension Value is List

您好,我有以下词典。

players = {
    "Brazil": [
        (12, "Júlio César", "Goalkeeper", []),
        (4, "David Luiz", "Defender", []),
        (6, "Marcelo", "Defender", []),
        (13, "Dante", "Defender", []),
        (23, "Maicon", "Defender", []),
        (5, "Fernandinho", "Midfielder", []),
        (7, "Hulk", "Midfielder", []),
        (8, "Paulinho", "Midfielder", []),
        (11, "Oscar", "Midfielder", [90]),
        (16, "Ramires", "Midfielder", []),
        (17, "Luiz Gustavo", "Midfielder", []),
        (19, "Willian", "Midfielder", []),
        (9, "Fred", "Striker", []),
    ],
    "Germany": [
        (1, "Manuel Neuer", "Goalkeeper", []),
        (4, "Benedikt Höwedes", "Defender", []),
        (5, "Mats Hummels", "Defender", []),
        (16, "Philipp Lahm", "Defender", []),
        (17, "Per Mertesacker", "Defender", []),
        (20, "Jérôme Boateng", "Defender", []),
        (6, "Sami Khedira", "Midfielder", [29]),
        (7, "Bastian Schweinsteiger", "Midfielder", []),
        (8, "Mesut Özil", "Midfielder", []),
        (13, "Thomas Müller", "Midfielder", [11]),
        (14, "Julian Draxler", "Midfielder", []),
        (18, "Toni Kroos", "Midfielder", [24, 26]),
        (9, "André Schürrle", "Striker", [69, 79]),
        (11, "Miroslav Klose", "Striker", [23]),
    ],
}

是否可以创建一个包含所有巴西球员的字典,在单行字典理解中以名字为键,第一个数字为值? 输出应为:

{'Júlio César': 12, 'David Luiz': 4, 'Marcelo': 6, 'Dante': 13, 'Maicon': 23, 'Fernandinho': 5, 'Hulk': 7, 'Paulinho': 8, 'Oscar': 11, 'Ramires': 16, 'Luiz Gustavo': 17, 'Willian': 19, 'Fred': 9}

当然可以!

brazil = {player: number for (number, player, _, _) in players["Brazil"]}

# {'Júlio César': 12, 'David Luiz': 4, 'Marcelo': 6, 'Dante': 13, 'Maicon': 23, 'Fernandinho': 5, 'Hulk': 7, 'Paulinho': 8, 'Oscar': 11, 'Ramires': 16, 'Luiz Gustavo': 17, 'Willian': 19, 'Fred': 9}

这通过从源数据扩展元组列表中的每个元组来实现。您要使用的键和值已命名,而下划线是表示您不想使用元组的那些部分的常规方式