Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read data and write to variables from dictionary

I have a dictionary like:

mapping = {"Filename1": 999, "Filename2": "998"}

I have a process where I define a variable ‘Filename1’ with:

import pandas as pd

read="Filename1"
code=999

df=pd.read_csv(f'{read}.csv')
df['new_col'] = code
Filename1 = df

In short, to read the filenames, add a new column with ‘code’, and write a new variable with same filename.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I loop this process through the dictionary so that it repeats for all filenames and their respective ‘codes’, and writes filenames as variables? Output is variables called ‘Filename1’, ‘Filename2’

>Solution :

How about

for read, code in mapping.items():
    df=pd.read_csv(f'{read}.csv')
    df['new_col'] = code
    df.to_csv(f'{read}_new.csv', index=False)

You haven’t specified how you want to write the DataFrame to disk, but you could modify the last line accordingly

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading