Quantcast
Channel: Active questions tagged header - Stack Overflow
Viewing all articles
Browse latest Browse all 699

Read csv with duplicate column headers in Python

$
0
0

I want to read a csv as a dictionary in Python, but now I encountered a problem, because the csv contains headers used more than once, like this:

idnamelabelslabels
01onemytaskmyproduct
02twomylabel

The standard way to import a csv to python looks like this:

# import csvimport csv# read csv file to a list of dictionarieswith open('data.csv', 'r') as file:    csv_reader = csv.DictReader(file)    data = [row for row in csv_reader]print(data)

Sadly this code swallows up the first 'labels' value if there is more than one. This code outputs this:

[    {'id': '01', 'name': 'one', 'labels': 'myproduct'},    {'id': '02', 'name': 'two', 'labels': 'mylabel'},]

Is there any way to read also the second value for 'labels' without getting to complicated? My preferred output would look like this:

[    {'id': '01', 'name': 'one', 'labels': ['mytask', 'myproduct']},    {'id': '02', 'name': 'two', 'labels': 'mylabel'},]

Viewing all articles
Browse latest Browse all 699

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>