Redis-py HINCRBY to increase a field value in hash

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)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like