I'm trying to populate Redis with data from CSV file in Python as below:
r = redis.Redis(host='localhost', port=6379, db=0)
with open('.../countries_list.csv') as csvfile: csv_reader = csv.DictReader(csvfile, delimiter =',', fieldnames = ['country', 'capital', 'population']) for row in csv_reader: country = row['country'] capital = row['capital'] population = row['population'] for row in csv_reader: country = row['country'] capital = row['capital'] population = (int(row['population'])) r.hmset(country, {'capital': capital, 'population': population})That's piece of code seems to be working fine. However, I would like now to increment the value of 'population' field for each country for which 'population' = 0. (change it from 0 to 1) I'm trying to use HINCRBY function and use simple for loop, but it does not change value in the database.
for row in csv_reader: if population < 1: r.hincrby('country', 'population', 1)Could you please help and advise what is done wrong? And how can I filter values in the most efficient way and actually increase them? Thank you.
1 Answer
You are using 'country' as a string not a variable.
for row in csv_reader: if population < 1: r.hincrby(country, 'population', 1)