简体   繁体   中英

How do I add multiple values to a key dictionary

I have a tour-de-france file and I would like to have years as the key and the other information as values.

Part of the file looks like this

Year,Cyclist,Time,Distance,Hours,Minutes,Seconds,Team,CyclistNumber,TotalSeconds,Gap,Stages
1903,MAURICE GARIN,94h 33' 14'',2428,94,33,14,TDF 1903 ***,1,340394,-,6
1903,LUCIEN POTHIER,97h 32' 35'',2428,97,32,35,TDF 1903 ***,37,351155,+ 02h 59' 21'',6
1903,FERNAND AUGEREAU,99h 02' 38'',2428,99,2,38,TDF 1903 ***,39,356558,+ 04h 29' 24'',6
1903,RODOLPHE MULLER,99h 12' 44'',2428,99,12,44,TDF 1903 ***,33,357164,+ 04h 39' 30'',6
1903,JEAN-BAPTISTE FISCHER,99h 41' 58'',2428,99,41,58,TDF 1903 ***,12,358918,+ 05h 08' 44'',6
1903,ARSENE MILLOCHEAU,155h 30' 44'',2428,155,30,44,TDF 1903 ***,67,559844,+ 60h 57' 30'',6

And I have made the following dictionary

with open("tour-de-france.csv") as file:
    reader = csv.reader(file)
    no_header = next(reader, None)
    new_dct = {}
    for x in reader:
        new_dct[x[0]] = x[1:]
    print(new_dct)

And part of the output looks like this:

{'1903': ['ARSENE MILLOCHEAU', "155h 30' 44''", '2428', '155', '30', '44', 'TDF 1903 ***', '67', '559844', "+ 60h 57' 30''", '6']

The output only has the last person of the year 1903 as the value, however is it also possible to have every person in the year of 1903 as value?

you can use the list of list as value ie

with open("tour-de-france.csv") as file:
    reader = csv.reader(file)
    no_header = next(reader, None)
    new_dct = {}
    for x in reader:
        new_dict.setdefault(x[0], [])
        new_dct[x[0]].append(x[1:])
    print(new_dct)

which will result in something like this

{'1903': [['MAURICE GARIN', ...], ['LUCIEN POTHIER', ...], ['FERNAND AUGEREAU', ...], ['RODOLPHE MULLER', ...], ['JEAN-BAPTISTE FISCHER', ...] ['ARSENE MILLOCHEAU', "155h 30' 44''", '2428', '155', '30', '44', 'TDF 1903 ***', '67', '559844', "+ 60h 57' 30''", '6']]

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