导致以下输出的我的代码和数据结构如下所示: 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)输出: Actions = {"{'command1': ['uptime'], 'path': ['/var/log/syslog']}", "{'command1': ['df -h'], 'path': ['/var/log/auth.log']}"}我需要分别提取命令和路径,这样的事情不起作用。 print(commands[0]['command1']) Traceback (most recent call last):文件“read_shell_yaml.py”,第 46 行,在 print(commands[0]['command1']) 类型错误:字符串索引必须是整数
2 回答

MMTTMM
TA贡献1869条经验 获得超4个赞
如果你需要按照你所做的方式来做,你可以在最后:
import json
content = json.loads(command[0].replace("'", '"'))
content['command1'] #prints ['df -h']

湖上湖
TA贡献2003条经验 获得超2个赞
您正在item使用str.format方法将dict格式化为字符串,这会阻止后一代码从 dict 中提取项目。
为了您的目的,更合适的数据结构Actions将是由命令索引的字典:
Actions = {}
for item in d['server']:
Actions[items.pop('command1')] = item
以便您以后可以Actions像这样遍历dict的项目:
for command, properties in Actions.items():
print(command, properties['path'])
添加回答
举报
0/150
提交
取消