I want to make a structure similar to:
structure = {value: {key: item}, value : {key: item}}
And I want to add this to redis in a similar way:
mapping = {}
for i, (key, item) in enumerate(sorted(total_activs.items()), start=1):
mapping[i] = {key: item}
r.hset(f"{group}", json.dumps(mapping))
but it doesn't work. But why?
In the future in the code I want to get 3 elements and work with dicts
top = r.hmget(f"{group}", ['1', '2', '3'])
print(top) # return [{key_1: my_first_item}, {key_2: my_second_item}]
top[0][key_1] # my_first_item
If you want to provide a mapping to r.hset()
, you need to fix two things:
mapping=
keyword, since it's the fourth positional argument.mapping = {}
for i, (key, item) in enumerate(sorted(total_activs.items()), start=1):
mapping[i] = json.dumps({key: item})
r.hset(f"{group}", mapping=mapping)
When you get the values, you'll want to parse the JSON to turn them back in dictionaries.
top = list(map(json.loads, r.hmget(f"{group}", ['1', '2', '3'])))