Reputation: 179
I'm trying to read a CSV file (i.e. a simple table) using python's csv
module and create a dictionary where the first column is the key and the second column is the value. My problem is that when I parse each row/line, the text from the second column gets formatted with brackets.
For example, assume that the pipes separate each column of the table:
City | Number
Houston | 1
Austin | 2
Dallas | 3
(Sorry for the poor formatting, but I couldn't figure out how to get Stack Overflow to format tables correctly, even after trying.)
My code is:
my_dict = defaultdict(list)
with open(my_file, newline='') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # Skip the row containing the column headers
for row in csv_reader:
region_name, region_code = row[0], int(row[1])
my_dict[region_name].append(region_code)
When I print my_dict
, I see that "Houston" has value [1], and not 1. I also see that "Austin" has value [2], and not 2. And the same goes for all other values.
More precisely, if I type:
print(my_dict["Houston"])
I get the value [1]
and not 1
.
I know that the csv
module converts each row/line to a list, but I don't know why the second column has brackets added to it. Why does this happen, and how can I get rid of the brackets?
Upvotes: 0
Views: 956
Reputation:
Why does this happen
Because you told python to use a list as the default value, i.e, defaultdict(list)
, and you then call .append(region_code)
on that list.
how can I get rid of the brackets?
my_dict = {}
with open(my_file, newline='') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # Skip the row containing the column headers
for row in csv_reader:
region_name, region_code = row[0], int(row[1])
my_dict[region_name] = region_code
Upvotes: 1