How to read data and write to variables from dictionary

Question:

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?

Asked By: Thelonious Monk

||

Answers:

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

Answered By: ignoring_gravity

Looping through dictionary:

for key in mapping:
    print(key, ', corresponds to: ', mapping[key])
Answered By: gtomer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.