python - exec - 提取一个值
python - exec - extracting a value
我正在尝试从看起来像“文本”的长字符串中提取一些信息。我有兴趣提取“阴影”的值:
>>> 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]
目前,我总是需要指定一个密钥(“1234”或“23”)。有没有办法在不知道密钥的情况下提取所有“阴影”值?输出可能如下所示:
[1, 2, 3]
[3, 4, 5]
我使用“exec”,但任何其他有效的方法都可以。我一直在寻找答案,但找不到任何解决方案。
在遍历字典的键时,检查是否有键为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]]
我正在尝试从看起来像“文本”的长字符串中提取一些信息。我有兴趣提取“阴影”的值:
>>> 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]
目前,我总是需要指定一个密钥(“1234”或“23”)。有没有办法在不知道密钥的情况下提取所有“阴影”值?输出可能如下所示:
[1, 2, 3]
[3, 4, 5]
我使用“exec”,但任何其他有效的方法都可以。我一直在寻找答案,但找不到任何解决方案。
在遍历字典的键时,检查是否有键为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]]