1

このプログラムが何を出力するかを理解しようとしていますが、関数が実際に何を出力するかについて問題があります

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()
4

2 に答える 2

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 - for ループが辞書用の'car', 'zebra'3 未満のキー値に遭遇すると、 and を生成し、 andを使用して値を持つキーとして初期化されるため、コードが出力されます。したがって、結果。1, 2d[1]d[2]"car""house""zebra"d['car'] = 'zebra'd['house'] = 'zebra'

于 2013-08-11T16:35:34.737 に答える