簡體   English   中英

從python中的嵌套字典結構中提取值

[英]Extracting values from a nested dictionary structure in 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'])TypeError:字符串索引必須為整數

您正在使用str.format方法將item dict格式化為字符串,這可以防止后面的代碼從dict中提取項目。

為了您的目的,更適合Actions數據結構將是由命令索引的dict,而不是:

Actions = {}
for item in d['server']:
    Actions[items.pop('command1')] = item

這樣您以后就可以遍歷Actions dict的各項,如下所示:

for command, properties in Actions.items():
    print(command, properties['path'])

如果您需要按照以前的方式進行操作,則可以在最后:

import json
content = json.loads(command[0].replace("'", '"'))
content['command1'] #prints ['df -h']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM