2013-05-06 116 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