My code and data structure that results in the output below looks like this :
Actions = set()
# loop through and obtain a list of files and commands
for item in d['server']:
Actions.add('{action}'.format(**item))
print(Actions)
commands = list(Actions)
commands = list(Actions)
Output:
Actions = {"{'command1': ['uptime'], 'path': ['/var/log/syslog']}", "{'command1': ['df -h'], 'path': ['/var/log/auth.log']}"}
I need to extract the commands and paths separately and something like this doesn't work.
print(commands[0]['command1'])
Traceback (most recent call last):
File "read_shell_yaml.py", line 46, in print(commands[0]['command1']) TypeError: string indices must be integers
You are formatting your item
dict into a string with the str.format
method, which prevents the latter code from extracting items from the dict.
For your purpose, a more fitting data structure for Actions
would be a dict indexed by the command instead:
Actions = {}
for item in d['server']:
Actions[items.pop('command1')] = item
so that you can later iterate through the items of the Actions
dict like this:
for command, properties in Actions.items():
print(command, properties['path'])
If you need to do it in the way that you did, you can at the end:
import json
content = json.loads(command[0].replace("'", '"'))
content['command1'] #prints ['df -h']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.