Home > Software engineering >  How can I get 1 value per key in a dictionary in python?
How can I get 1 value per key in a dictionary in python?

Time:09-05

I am aware that dictionaries should already have a single value per key, but in my case I made a dictionary from a csv file (which can NOT be modified in any way). This csv file has 2 columns and instead of getting the first column as keys and the second as values, I get the first row as keys (so 2 keys) and everything else as values. Is there any way to modify this in python and get the first column as keys and the second as values?

The code is basically:

import pandas as pd
df = pd.read_csv('data.csv')
dict = df.to_dict()

CodePudding user response:

Can you use pandas? If so, the following will work:

import pandas as pd

df = pd.read_csv('your_file.csv')

your_dict = df.set_index('A')['B'].to_dict()

This assumes your columns are named A and B, where A is the key and B is the value.

CodePudding user response:

You don't have to use pandas, just read the file into dict() (the built-in dict, not the override from your code)

with open('file.csv', 'r') as file:
    d = dict(line.strip().split(',') for line in file.readlines())
  • Related