Home > Mobile >  How to read data and write to variables from dictionary
How to read data and write to variables from dictionary

Time:09-01

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.

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?

CodePudding user response:

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

CodePudding user response:

Looping through dictionary:

for key in mapping:
    print(key, ', corresponds to: ', mapping[key])
  • Related