如何将字典的特定属性设置为[]

New*_*ing 1 python dictionary

让我们想象下面的字典

dictionary = {
    "key1": {
         "value": [1, 3, 5],
     },

    "key2": {
         "value": [1, 2, -1],
     },
}
Run Code Online (Sandbox Code Playgroud)

是否可以将所有内容设置"values"[]不重复字典键?我想要这样的东西dictionary[]["value"]=[],所有"值"属性都设置为[].但这不起作用.

Aus*_*tin 5

因为你需要避免迭代,所以这是解决案例的一种问题.

将字典转换为字符串,替换然后再返回字典:

import re, ast

dictionary = {
    "key1": {
         "value": [1, 3, 5],
     },

    "key2": {
         "value": [1, 2, -1],
     },
}

print(ast.literal_eval(re.sub(r'\[.*?\]', '[]', str(dictionary))))
# {'key1': {'value': []}, 'key2': {'value': []}}
Run Code Online (Sandbox Code Playgroud)

  • "一点".对:) :) (2认同)
  • 这如何避免迭代?您可能没有编写for循环,但您认为如何生成repr?它也非常脆弱. (2认同)