从列表中访问字典

时间:2013-05-06 06:44:27

标签: python

我有一些字典如下

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

字典键的值包含列表
和一个清单,

l1=[d1,d2,d3]

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

如何通过列表访问所有这些词典?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]

答案 2 :(得分: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__ on a module