2012-10-10 39 views
2

我已經構造一個字典是這樣的:如何迭代和搜索字典?

dir是:

{((2, 1), 'South', 1): set([((2, 2), 'South', 1)]), 
((1, 3), 'South', 1): set([((1, 4), 'South', 1)]), 
((5, 3), 'East', 1): set([((4, 3), 'North', 1)]), 
((2, 2), 'South', 1): set([((2, 3), 'East', 1)]), 
((4, 2), 'East', 1): set([((3, 2), 'East', 1)]), 
((1, 1), 'West', 1): set([((2, 1), 'South', 1)])} 

我想要遍歷通過這個詞典是這樣的:

如果我有((2, 1), 'South', 1)作爲重點,那麼我D喜歡提取它的值set([((2,2),'South',1)]),並將其作爲密鑰並通過搜索並找到它的值等等......

但是我無法爲此構建函數。我不斷獲得一個價值,並且無限循環。我想我可能會錯誤地將值取值。有人可以告訴我怎麼做到這一點?

+6

表明你有嘗試過的代碼。 – BrenBarn

+1

@calccrypto:這是一個'dict'。爲什麼不使用直接訪問? 'dir_is [((2,1),'South',1)]' – inspectorG4dget

+0

@ inspectorG4dget herpaderp。但OP沒有說迭代 – calccrypto

回答

-1

試試這個:

def iterate_get_value(my_dict): 
    for k,v in my_dict.iteritems(): 
     if k == ((2, 1), 'South', 1): 
      return v 

這是否對你的工作?

+0

@downvoter:謹慎地告訴我爲什麼這是一個壞的帖子? – inspectorG4dget

0

據我所知,你需要什麼。試試這個:

start_pos = ((2, 1), 'South', 1) 

d = {...} 

visited = set() 

def go(pos): 
    visited.add(pos) 
    for v in d[pos]: 
     if v not in visited: 
      go(v) 

go(start_pos) 
1

如何如下:

key = ((2, 1), 'South', 1) 
while (x.has_key(key)): 
    print x[key] 
    key = iter(x[key]).next() 
+0

'while(dirr.has_key [key]): TypeError:'builtin_function_or_method'對象沒有屬性'__getitem __'' 錯誤:( – Saturnian