python - exec - 提取一个值

时间:2021-08-01 19:42:15

标签: python exec

我试图从看起来像“文本”的长字符串中提取一些信息。我有兴趣提取“阴影”的值:

rdNew.Hazards

现在,我总是需要指定一个键(“1234”或“23”)。有没有办法在不知道密钥的情况下提取所有“阴影”值?输出可能如下所示:

>>> text = 'colors = {\r\n\r\n    "1234": {\r\n        "shade": [1, 2, 3]},   "23": {"shade": [3,4,5]}\r\n}\r\n'
>>> exec(text)
>>> print(colors['1234']['shade'])
[1, 2, 3]
>>> print(colors['23']['shade'])
[3, 4, 5]

我使用“exec”,但任何其他有效的方法都可以。我正在寻找答案,但找不到任何解决方案。

1 个答案:

答案 0 :(得分:0)

在遍历字典的键时,检查它是否有键为shade的内部字典。您可以使用 for 循环或列表推导来实现:

# First solution
>>> for key in colors.keys():
    if colors[key].get('shade', False):
        print(colors[key]['shade'])

        
[1, 2, 3]
[3, 4, 5]

# Second solution
>>> res = [colors[key]['shade'] for key in colors.keys() if colors[key].get('shade', False)]
>>> res
[[1, 2, 3], [3, 4, 5]]