2016-04-21 97 views
2

因此,我需要在python中定義一些函數,以分別爲每個值打印每個字典鍵。一切都是機場代碼,例如,輸出應該看起來像「從ORD到JFK有直接航班」。而且我需要爲每個機場的每次直飛打印。通過字典中的鍵循環

下面是一個例子輸入

{"ORD" : ["JFK", "LAX", "SFO"], 
"CID" : ["DEN", "ORD"], 
"DEN" : ["CID", "SFO"], 
"JFK" : ["LAX"], 
"LAX" : ["ORD"], 
"SFO" : []} 

我的功能是

def printAllDirectFlights(flightGraph): 
    x = len(flightGraph) 
    y = 0 
    while y < x: 
     n = len(flightGraph[y]) 
     z = 0 
     while z < n: 
      print("There is a direct flight from",flightGraph[y],"to",flightGraph[y][z],".") 

我想這會工作,但顯然我錯了。我如何通過按鍵循環?我知道,如果我是,例如寫

print(flightGraph["ORD"][0]) 

然後我會收到JFK作爲輸出,但我怎麼去通過字典的鍵循環? 。

回答

0

您可以通過執行for key in d:(這相當於for key in d.keys()遍歷在字典d鍵下面的示例:

d = {'a': 1, 'b': 2} 
for key in d: 
    print key 

會打印:

a 
b 
+0

好的,這是有道理的。我修改了代碼,使d = flightGraph。我的第一個循環是鍵入d。但是,當我嘗試運行它時,按照此順序得到。 LAX CID SFO ORD JFK LAX SFO DEN ORD,爲什麼是爲了看似隨意? – CabooseMSG

0

使用items()

for k,v in flightGraph.items(): 
    for c in v: 
     print("There is a direct flight from " + k + " to " + c) 


There is a direct flight from ORD to JFK 
There is a direct flight from ORD to LAX 
There is a direct flight from ORD to SFO 
There is a direct flight from CID to DEN 
There is a direct flight from CID to ORD 
There is a direct flight from JFK to LAX 
There is a direct flight from DEN to CID 
There is a direct flight from DEN to SFO 
There is a direct flight from LAX to ORD 

使用sorted(flightGraph.items())如果你想第一個城市按字母順序排列:

for k,v in sorted(flightGraph.items()): 
     for c in v: 
      print("There is a direct flight from " + k + " to " + c) 

There is a direct flight from CID to DEN 
There is a direct flight from CID to ORD 
There is a direct flight from DEN to CID 
There is a direct flight from DEN to SFO 
There is a direct flight from JFK to LAX 
There is a direct flight from LAX to ORD 
There is a direct flight from ORD to JFK 
There is a direct flight from ORD to LAX 
There is a direct flight from ORD to SFO 
+0

謝謝你的幫助! – CabooseMSG

0

如果鍵的長度可超過1作爲一個更一般的方式,你可以遍歷所有的鍵與他們相對的產品值,並得到所有的對:

>>> from itertools import product 
>>> for k, v in the_dict.items(): 
...  for i, j in product((k,), v): 
...  print("There is a direct flight from {} to {}".format(i, j)) 
... 
There is a direct flight from JFK to LAX 
There is a direct flight from CID to DEN 
There is a direct flight from CID to ORD 
There is a direct flight from LAX to ORD 
There is a direct flight from DEN to CID 
There is a direct flight from DEN to SFO 
There is a direct flight from ORD to JFK 
There is a direct flight from ORD to LAX 
There is a direct flight from ORD to SFO 

注意的是,雖然dict.items不給你一個有序的結果,如果你想獲得的訂單爲您的輸入順序,你最好使用OrderedDictcollection模塊保護你鍵值對。

+0

謝謝,我感謝您的幫助! – CabooseMSG