Home > Enterprise >  create a list of categories from a dictionary in Python
create a list of categories from a dictionary in Python

Time:11-12

`

import csv

record={}
with open( 'subject-info.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        record[row['ID']]=row['Age_group']

` now the dictionary has ID number as keys and the value of each key has one number between 1 and 13. each number represents an age group.

I need to put together all the IDs that are in the same age group in seprate lists or dictionaries . How do I do that please? thank you

I am not sure how to continue

CodePudding user response:

import csv

record_list=[]
with open( 'subject-info.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        record_dict={}
        record_dict[row['ID']]=row['Age_group']
        record_list.append(record_dict)

I hope this might help you. Good day!

CodePudding user response:

I finally found the answer and I want to post it here :

age_group=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 
           '13', '14', '15']    
mydict={ag:[] for ag in age_group}
with open ('subject-info.csv') as f:
    reader=csv.DictReader(f)
    for row in reader:
        if row['Age_group']=='NaN':
            pass            
        else:
        
            mydict[row['Age_group']].append(row['ID'])
  • Related