Reputation: 79
I have a question regarding how to match variables to DictReader headers and rows.
I have the below set from a CSV:
OrderedDict([('name', 'Bob'), ('cash', '2'), ('food', '8'), ('drink', '11')])
OrderedDict([('name', 'Mary'), ('cash', '3'), ('food', '9'), ('drink', '2')])
I also have variables I'm taking from another file.
maximum_number
is a counter of the greatest repeating categories, and maximum_category
is the associated category.
with open(database_name, newline='') as csvfile:
dictionary = csv.DictReader(csvfile)
for row in dictionary:
if maximum_number in row[maximum_category]:
print(row['name'])
For example, if maximum_category
is food and the maximum_number
is 9, I want to return Mary
(from name) from the above two sets. If the category is drink and number is 11, I want to return Bob
.
I'm in the middle of experimenting with Python, so I'm probably missing something basic, but I would like some advice as to why the above won't work and what's the best way to go about it.
Upvotes: 1
Views: 59
Reputation: 123501
You haven't indicated exactly how your code "won't work", but it seems to for me. Here's a runnable example using the following .csv file:
name,cash,food,drink
Bob,2,8,11
Mary,3,9,2
Code:
import csv
database_name = 'ordered_dict_test.csv'
maximum_category = 'food'
maximum_number = '9'
with open(database_name, newline='') as csvfile:
dictionary = csv.DictReader(csvfile)
for row in dictionary:
if maximum_number in row[maximum_category]:
print(row['name'])
maximum_category = 'drink'
maximum_number = '11'
with open(database_name, newline='') as csvfile:
dictionary = csv.DictReader(csvfile)
for row in dictionary:
if maximum_number in row[maximum_category]:
print(row['name'])
And prints the following:
Mary
Bob
I suspect the problem might be not realizing that all the data read and returned by the DictReader
are strings.
Upvotes: 1