gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:14 25 4
gpt4 key购买 nike

让我们想象一下下面的字典

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': []}}

关于python - 如何将字典的特定属性设置为 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com