为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥6287543 2021-09-14 15:53:21
导致以下输出的我的代码和数据结构如下所示:    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']


查看完整回答
反对 回复 2021-09-14
?
湖上湖

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'])


查看完整回答
反对 回复 2021-09-14
  • 2 回答
  • 0 关注
  • 276 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号