[Python] How to print specific keys and values from list of dict's on one line in python

Discussão em 'Python' iniciado por Stack, Janeiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    This is my list of dictionary's, which is part of a larger dictionary containing numerous lists

    competitorRankDetails": [
    {
    "phaseCode": "M1",
    "phaseName": "Moto 1",
    "phaseBlockCode": "M1",
    "rank": 1,
    "raceName": "46",
    "racePosition": 6,
    "result": 1,
    "score": 1,
    "hillTime": "2.754",
    "time": "30.755"
    },
    {
    "phaseCode": "M2",
    "phaseName": "Moto 2",
    "phaseBlockCode": "M2",
    "rank": 1,
    "raceName": "97",
    "racePosition": 7,
    "result": 1,
    "score": 2,
    "hillTime": "2.732",
    "time": "30.689"
    },
    {
    "phaseCode": "M3",
    "phaseName": "Moto 3",
    "phaseBlockCode": "M3",
    "rank": 1,
    "raceName": "148",
    "racePosition": 3,
    "result": 1,
    "score": 3,
    "hillTime": "2.745",
    "time": "30.692"
    }


    This is the print statement I've tried to get the output I'm looking for

    info = ['phaseName', 'racePosition', 'hillTime']

    for record in item['competitorRankDetails']:
    print(*record,[record[k] for k in info])


    This results in the following output

    phaseCode phaseName phaseBlockCode rank raceName racePosition result score hillTime time ['Moto 1', 7, '2.883']
    phaseCode phaseName phaseBlockCode rank raceName racePosition result score hillTime time ['Moto 2', 5, '2.882']
    phaseCode phaseName phaseBlockCode rank raceName racePosition result score hillTime time ['Moto 3', 2, '2.887']


    Is there a way I could have the output like below with the possibility to add more items to info

    phaseName: Moto1 , racePosition: 7 , hillTime: 2.878
    PhaseName: Moto2 , racePosition: 6 , hillTime: 2.856
    PhaseName: Moto3 , racePosition: 1 , hillTime: 2.885

    Continue reading...

Compartilhe esta Página