如何在python中遍历以下dict

时间:2016-03-21 11:31:21

标签: python

我有一个dict,其中每个索引都有数组作为值。我想检索每个数组并打印该数组中的每个值以及索引。我该怎么做?

{'bridge0': [snic(family=18, address='3a:c9:86:61:01:00', netmask=None, broadcast=None, ptp=None)], 
'lo0': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snic(family=30, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snic(family=30, address='fe80::1%lo0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)],
'en0': [snic(family=18, address='38:c9:86:16:8c:c9', netmask=None, broadcast=None, ptp=None)],
'en1': [snic(family=2, address='192.168.1.37', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), snic(family=18, address='38:c9:86:3a:2a:7a', netmask=None, broadcast=None, ptp=None), snic(family=30, address='fe80::3acd:86ff:feea:2a7a%en1', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)],
'en2': [snic(family=18, address='d2:00:1d:98:9b:d0', netmask=None, broadcast=None, ptp=None)],
'p2p0': [snic(family=18, address='1a:c9:86:ea:2a:7b', netmask=None, broadcast=None, ptp=None)],
'awdl0': [snic(family=18, address='66:f7:08:8a:1f:d3', netmask=None, broadcast=None, ptp=None), snic(family=30, address='fe80::64f7:8ff:fe8a:1fc3%awdl0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)],
'vboxnet0': [snic(family=2, address='192.168.99.1', netmask=None, broadcast='192.168.99.255', ptp=None), snic(family=18, address='0a:00:27:00:00:10', netmask=None, broadcast=None, ptp=None)],
'fw0': [snic(family=18, address='08:74:02:ff:fe:d9:89:bx', netmask=None, broadcast=None, ptp=None)]}<br>

这就是我的尝试。netw是上面的词典:

 for x,y in netw:
       print x
       print y

2 个答案:

答案 0 :(得分:1)

当您在Python中迭代字典时,您将获得其密钥。如果您想要键和值,请迭代字典的items()

for key, value in netw.items():
    # maybe iterate again over the value list here?
    print  key, value

在Python 2上,如果您的字典有很多值,您可能希望使用iteritems()而不是items()(前者返回迭代器,而不是将所有项放在列表中)。在Python 3中,items()返回&#34;视图&#34; object,它是一个轻量级的迭代,与Python 2中iteritems返回的迭代器没有太大区别。

答案 1 :(得分:0)

你可以先获得字典d的键。 然后通过字典的每个键访问数组。

for k in d.keys():
    for i in range(len(d[k])):
        print "d["+k+"]["+i+"]="+d[k][i]