最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How set bult-in dict in Redis - Stack Overflow

programmeradmin9浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 1

If 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'])))
发布评论

评论列表(0)

  1. 暂无评论