How can I loop through this dictionary instead of hardcoding the keys

后端 未结 4 1582
长发绾君心
长发绾君心 2021-01-21 18:47

So far, I have this code (from cs50/pset6/DNA):

import csv

data_dict = {}
with open(argv[1]) as data_file:
    reader = csv.DictReader(data_file)
    for record          


        
4条回答
  •  伪装坚强ぢ
    2021-01-21 19:18

    You could also try using pandas.

    Using your example data as .csv file:

    pandas.read_csv('example.csv', index_col = 0).transpose().to_dict()
    

    Outputs:

    {'Alice': {'AGATC': 2, 'AATG': 8, 'TATC': 3},
     'Bob': {'AGATC': 4, 'AATG': 1, 'TATC': 5},
     'Charlie': {'AGATC': 3, 'AATG': 2, 'TATC': 5}}
    

    index_col = 0 because you have names column which I set as index (so that later becomes top level keys in dictionary)

    .transpose() so top level keys are names and not features (AGATC, AATG, etc.)

    .to_dict() to transform pandas.DataFrame to python dictionary

提交回复
热议问题