How to use a Python dictionary?

前端 未结 7 1061
闹比i
闹比i 2020-12-11 21:24

I am finding it difficult to iterate through a dictionary in python.

I have already finished learning via CodeAcademy and solo learn but still find it tough to go th

7条回答
  •  庸人自扰
    2020-12-11 21:51

    # In Python 3.x
    
    hash={'a': 1, 'b': 2}
    
    for k in hash:
        print (str(k) + "," + str(hash[k]))
    
    # OR
    for key, value in hash.items():
        print (str(key) + ',' + str(value))
    
    # OR
    for key, value in {'a': 1, 'b': 2}.items():
        print (str(key) + ',' + str(value))
    
    # OR
    for tup in hash.items():
        print (str(tup[0]) + ',' + str(tup[1]))
    

提交回复
热议问题