2017-03-28 115 views
-2

雖然,我遇到了很多嵌套字典的例子,但我無法破解這一個!以下是以json格式輸入和我想要的輸出,如下所示。 輸入字典有超過100個條目,我想只提取少數選定變量的值(如IP地址,Med,Active)。python從複雜的嵌套字典和列表中提取值

對於某些條目 '配有' 嵌套在列表[0,1,2等]

MED = BGP ['10 .0.0.0/16 '] [' bgpRoutePaths'] [0]。得到( '配有')
MED = BGP ['10 .0.0.0/16 '] [' bgpRoutePaths '] [1]獲得(' 配有')

Input: 

    {u'10.0.0.0/16': {u'address': u'10.0.0.0', 
          u'bgpAdvertisedPeerGroups': {}, 
          u'bgpRoutePaths': [{u'asPathEntry': {u'asPath': u'65404,65315 i',    
                   u'asPathType': None}, 
               u'localPreference': 100, 
               u'med': 0, 
               u'nextHop': u'172.1.1.169', 
               u'routeType': {u'active': True, 
                  u'atomicAggregator': False, 
                  u'backup': False, 
                  u'ecmp': False, 
                  u'ecmpContributor': False, 
                  u'ecmpHead': False, 
                  u'queued': False, 
                  u'stale': False, 
                  u'suppressed': False, 
                  u'ucmp': False, 
                  u'valid': True}, 
               u'weight': 0}, 
              {u'asPathEntry': {u'asPath': u'65407 65315 65317 65000 i', 
                   u'asPathType': None}, 
               u'localPreference': 100, 
               u'med': 0, 
               u'nextHop': u'172.16.1.94', 
               u'routeType': {u'active': False, 
                  u'atomicAggregator': False, 
                  u'backup': False, 
                  u'ecmp': False, 
                  u'ecmpContributor': False, 
                  u'ecmpHead': False, 
                  u'queued': False, 
                  u'stale': False, 
                  u'suppressed': False, 
                  u'ucmp': False, 
                  u'valid': True}, 
               u'weight': 0}], 
          u'maskLength': 16}, 
} 

輸出:

IPaddr   asPath        med active 
10.0.0.0/16 (65404 65315 i)      0 True 
10.0.0.0/16 (65407 65315 65317 65000 i)   0 False 
+0

你的實際問題是什麼? – Olaia

回答

0

考慮您的字典作爲變量「a」,那麼你可以通過

print a.keys()[0] 
print a['10.0.0.0/16']['bgpRoutePaths'][0]['asPathEntry']['asPath'], ' ', a['10.0.0.0/16']['bgpRoutePaths'][0]['med'], ' ', a['10.0.0.0/16']['bgpRoutePaths'][0]['routeType']['active'] 


print a['10.0.0.0/16']['bgpRoutePaths'][1]['asPathEntry']['asPath'], ' ', a['10.0.0.0/16']['bgpRoutePaths'][1]['med'], ' ', a['10.0.0.0/16']['bgpRoutePaths'][1]['routeType']['active'] 
0

我能解決這個我訪問的數據!

for k,v in a.iteritems(): 
    add = k 
    for i in range (0,len(a.values()[0]['bgpRoutePaths'])): 
    aspath = a.values()[0]['bgpRoutePaths'][i]['asPathEntry'].get('asPath') 
    active = a.values()[0]['bgpRoutePaths'][i]['routeType'].get('active') 
    print add,aspath,med,active 

Output: 
10.0.0.0/16 65404,65315 i 0 True 
10.0.0.0/16 65407 65315 65317 65000 i 0 False