2014-09-19 94 views
-3

我正在写一个脚本,它在一个特定的类别中运行一组不同的linux命令。 例如,提供系统信息的命令位于名为SYS_INFO的类别中。python阅读复杂的嵌套json值

我使用字典定义的命令(以及关于它们的详细信息)像这样

dictionary = { 
       "SYS_INFO": { 
       "Uname": { 
        "msg":"Kernel Version Information", 
        "cmd":"uname -a" 
        }, 
        "OS": { 
        "msg":"Operating System Information", 
        "cmd":"cat /etc/issue" 
        }, 
       "NET_INFO": { 
        etc... 
       } 
       } 

我翻翻字典,需要循环,并获得“类别”(UNAME,OS)和相关他们的信息(msg,cmd),不同的信息(SYS_INFO,NET_INFO)。

如何迭代字典并获取所需的信息?

+1

https://docs.python.org/2/tutorial/datastructures.html#dictionaries – jonrsharpe 2014-09-19 22:16:45

回答

1

一种方法是是这样的:

for k1 in dictionary: 
    for k2 in dictionary[k1]: 
     print k1, k2, dictionary[k1][k2] 

另一种方式是

for k1, d1 in dictionary.items(): 
    for k2, v in d1.items(): 
     print k1, k2, v