0

我有一些字典如下

d1={}  
d2={}  
d3={}  

字典键的值包含列表
和列表,

l1=[d1,d2,d3]

list 包含所有可用字典的名称。我想遍历包含所有字典名称的列表中可用的所有字典。

我如何通过 list 访问所有这些字典?

4

3 回答 3

5
>>> l1 = [d1,d2,d3]
>>> for d in l1:
        for k,v in d.items():
              print(k,v)

一个更好的例子

d1 = {"a":"A"}
d2 = {"b":"B"}
d3 = {"c":"C"}
l1 = [d1,d2,d3]
for d in l1:
    for k,v in d.items():
        print("Key = {0}, Value={1}".format(k,v))

生产

>>> 
Key = a, Value=A
Key = b, Value=B
Key = c, Value=C

如果它们仅包含字典的名称,即"d1"您可以执行以下操作(产生与上述相同的结果):

d1 = {"a":"A"}
d2 = {"b":"B"}
d3 = {"c":"C"}
l1 = ['d1','d2','d3']
for dname in l1:
    for k,v in globals()[dname].items():
        print("Key = {0}, Value={1}".format(k,v))

虽然我不推荐这种方法。(注意:如果字典在本地范围内,您也可以使用 locals())

当你有一个字典,它有一个与键关联的列表时,你可以像这样遍历列表:

d1 = {"a":[1,2,3]}
d2 = {"b":[4,5,6]}
l1=["d1","d2"]

for d in l1:
    for k,v in globals()[d].items(): #or simply d.items() if the values in l1 are references to the dictionaries
        print("Dictionray {0}, under key {1} contains:".format(d,k))
        for e in v:
            print("\t{0}".format(e))

生产

Dictionray d1, under key a contains:
    1
    2
    3
Dictionray d2, under key b contains:
    4
    5
    6
于 2013-05-06T06:48:29.310 回答
0
d1 = {'a': [1,2,3], 'b': [4,5,6]}
d2 = {'c': [7,8,9], 'd': [10,11,12]}
d3 = {'e': [13,14,15], 'f': [16,17,18]}

l1 = [d1,d2,d3]

for idx, d in enumerate(l1):
    print '\ndictionary %d' % idx
    for k, v in d.items():
        print 'dict key:\n%r' % k
        print 'dict value:\n%r' % v

产生:

dictionary 0
dict key:
'a'
dict value:
[1, 2, 3]
dict key:
'b'
dict value:
[4, 5, 6]

dictionary 1
dict key:
'c'
dict value:
[7, 8, 9]
dict key:
'd'
dict value:
[10, 11, 12]

dictionary 2
dict key:
'e'
dict value:
[13, 14, 15]
dict key:
'f'
dict value:
[16, 17, 18]
于 2013-05-06T07:00:59.600 回答
0

你需要“gettattr”吗?

http://docs.python.org/2/library/functions.html#getattr

http://effbot.org/zone/python-getattr.htm

class MyClass:
    d1 = {'a':1,'b':2,'c':3}
    d2 = {'d':4,'e':5,'f':6}
    d3 = {'g':7,'h':8,'i':9}

myclass_1 = MyClass()    
list_1 = ['d1','d2','d3']

dict_of_dicts = {}
for k in list_1:
    dict_of_dicts[k] = getattr(myclass_1, k)

print dict_of_dicts

或者,如果您想“全局”应用这个,请阅读如何在此处相对于模块使用“getattr”:模块上的 __getattr__

于 2013-05-06T07:01:45.350 回答