admin管理员组文章数量:1394534
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
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
Share
Improve this question
edited Mar 27 at 14:54
Barmar
784k57 gold badges548 silver badges660 bronze badges
asked Mar 27 at 10:58
YuniversiaYuniversia
76 bronze badges
1
- "doesn't work" is not a sufficient problem description. What are you expecting, what are you getting instead? – Barmar Commented Mar 27 at 14:53
1 Answer
Reset to default 1If you want to provide a mapping to r.hset()
, you need to fix two things:
- You must use the
mapping=
keyword, since it's the fourth positional argument. - You shouldn't encode the mapping as JSON, it must be a dictionary. Only the dictionary values should be encoded.
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'])))
本文标签: pythonHow set bultin dict in RedisStack Overflow
版权声明:本文标题:python - How set bult-in dict in Redis - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744094782a2590083.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论