从python中的嵌套字典结构中提取值

导致以下输出的我的代码和数据结构如下所示:


    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']) 类型错误:字符串索引必须是整数


慕哥6287543
浏览 277回答 2
2回答

MMTTMM

如果你需要按照你所做的方式来做,你可以在最后:import jsoncontent = json.loads(command[0].replace("'", '"'))content['command1'] #prints ['df -h']

湖上湖

您正在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'])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python