2016-04-21 91 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