I'm trying to extract some information from a long string that looks like "text". I am interested in extracting a value of "shade":
>>> 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]
For now, I always need to specify a key ("1234" or "23"). Is there a way to extract all "shade" values without knowing the key? The output could look like this:
[1, 2, 3]
[3, 4, 5]
I use "exec", but any other method that works will be fine. I was searching for the answer, but I couldn't find any solution.
While iterating through the keys of dictionary, check whether it has inner dictionary with the key of shade
or not. You could do it either using for
loop or list comprehension:
# 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]]