導(dǎo)致以下輸出的我的代碼和數(shù)據(jù)結(jié)構(gòu)如下所示: 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']) 類型錯(cuò)誤:字符串索引必須是整數(shù)
2 回答

MMTTMM
TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果你需要按照你所做的方式來做,你可以在最后:
import json
content = json.loads(command[0].replace("'", '"'))
content['command1'] #prints ['df -h']

湖上湖
TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
您正在item使用str.format方法將dict格式化為字符串,這會(huì)阻止后一代碼從 dict 中提取項(xiàng)目。
為了您的目的,更合適的數(shù)據(jù)結(jié)構(gòu)Actions將是由命令索引的字典:
Actions = {}
for item in d['server']:
Actions[items.pop('command1')] = item
以便您以后可以Actions像這樣遍歷dict的項(xiàng)目:
for command, properties in Actions.items():
print(command, properties['path'])
添加回答
舉報(bào)
0/150
提交
取消