Python打印功能

时间:2013-08-11 16:33:51

标签: python dictionary

我试图弄清楚这个程序将打印什么,我在实际打印的功能上遇到了麻烦

def main():
d = {1 : "car",
     2 : "house",
     3 : "boat",
     4 : "dog",
     5 : "kitchen"} 

L = list(d.keys()) #i know that here a list L is created with values [1,2,3,4,5]
i = 0 
while i < len(L):# while i is less than 5 because of length of list L
    k = L[i]     # k = l[0] so k == 1
    if k < 3 :   # if 1 < 3
     d[ d[k] ] = "zebra" d[ d[1] ] = #zebra so it adds zebra to the dictionary key 1    #right?

    i += 1      # here just i += 1 simple enough and while loop continues
                # loop continues and adds zebra to dictionary key 2 and stops
 for k in d :   
    print(k, d[k]) #This is were im having trouble understanding how everything is printed

main()

2 个答案:

答案 0 :(得分:1)

d = {
    1 : "car",
    2 : "house",
    3 : "boat",
    4 : "dog",
    5 : "kitchen"
} 

for key, value in d.items():
    print (key, value)

for key in d.keys():
    print (key, d[key])

for key in d:
    print (key, d[key])

最后两个循环是等效的。

  

我想知道为什么最后两行正在打印

第一次循环:

k=1

所以d [k]相当于

d[1]

所以

d[ d[k] ] 

相当于

d[ d[1] ]

d[1] is "car"

这样就可以了

d[ 'car' ]

并且代码执行此操作:

d[ 'car' ] = 'zebra'

答案 1 :(得分:0)

您可以使用for elem in testDict迭代字典的键,代码就是这样做并获取每个键的值并打印它。如果您对订单感到困惑,请注意字典没有订单,因此,按键和值不会以任何顺序打印。

类似的东西:

>>> testDict = {'a':1, 'b':2, 'c':3}
>>> for elem in testDict:
print('Key: {}, Value: {}'.format(elem, testDict[elem]))


Key: a, Value: 1
Key: c, Value: 3
Key: b, Value: 2

UPDATE - 代码打印'car', 'zebra'等等,因为当for循环遇到小于3的键值(字典为1, 2时), d[1]d[2]会产生"car""house",然后使用"zebra"d['car'] = 'zebra'将其初始化为值为d['house'] = 'zebra'的键因此结果。