让我们想象一下下面的字典
dictionary = {
"key1": {
"value": [1, 3, 5],
},
"key2": {
"value": [1, 2, -1],
},
}
是否可以在不遍历字典键的情况下将所有 "values" 设置为 []?我想要像 dictionary[]["value"]=[] 这样的东西,这样所有“值”属性都设置为 []。但这不起作用。
请您参考如下方法:
因为您需要避免迭代,这里有一个小技巧的解决方法。
将字典转换为字符串,替换然后返回字典:
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': []}}
