2013-05-06 93 views
0

我有一些字典如下字典键的访问字典

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

值包含列表
和一个列表,

l1=[d1,d2,d3] 

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

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

+2

看起来更像列表中包含引用的字典,而不是他们的名字。那是对的吗? – 2013-05-06 06:47:13

+0

它只是包含名称。不知道我是否可以在这种情况下使用参考。如果是,那么如何? – 2013-05-06 06:49:28

+0

如果'd1'是一个变量,并且你编写了'l1 = [d1]',那么这个列表包含对'd1'的值的引用,而不是'd1'的名称。如果你使用了一个字符串,比如'l1 = ['d1']',那会让事情变得更加复杂。 – 2013-05-06 06:57:26

回答

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)) 

虽然我不会推荐这种方法。 (注:你也可以你的当地人()如果字典是在局部范围内)

当你拥有它有一个键相关联的列表中的词典,你可以去在列表上,像这样:

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 
+0

忘了提及**字典键的值包含列表** – 2013-05-06 06:54:06

+0

@RameshRaithatha请参阅我的答案的补充,这有帮助吗? – HennyH 2013-05-06 06:59:57

+0

非常感谢,帮助! :) – 2013-05-06 07:13:09

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] 
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

+0

这是一个非常迂回的方式来创建一个字典的字典。为什么不直接跳到字典的字典,这是一个更明智的解决方案。 – Marius 2013-05-06 07:06:21

+0

的目的是为了演示“getattr” – StefanNch 2013-05-06 07:13:25