简体   繁体   中英

Dictionary Comprehension Value is List

Hi i have following Dictionary.

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]),
    ],
}

Is it possible to create a dictionary which contains all Brazilian players with the name as key and the first number as value in a one line dictionary comprehension? Output should be:

{'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}

Sure it's possible!

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}

This works by expanding each tuple in the list of tuples from your source data. The key and value you want to use are named, while the underscores are a conventional way of saying you don't want to use those parts of the tuple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM