循环通过字典中的键

时间:2016-04-21 18:27:13

标签: python dictionary key cycle

所以我需要在python中定义一些函数,它将分别打印每个字典键和每个值。一切都是机场代码,所以输出,例如,应该看起来像#34;从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作为输出,但我如何循环通过字典的键?

3 个答案:

答案 0 :(得分:0)

您可以通过d(相当于for key in d:来迭代字典for key in d.keys()中的键。示例如下:

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

将打印:

a
b

答案 1 :(得分: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

答案 2 :(得分: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没有为您提供有序结果,但如果您想要将订单作为输入订单,则最好使用OrderedDict模块中的collection用于保留键值对。