How do you find the first key in a dictionary?

前端 未结 12 881
清酒与你
清酒与你 2020-11-27 10:58

I am trying to get my program to print out \"banana\" from the dictionary. What would be the simplest way to do this?

This is my dictionary:

         


        
12条回答
  •  迷失自我
    2020-11-27 11:40

    As many others have pointed out there is no first value in a dictionary. The sorting in them is arbitrary and you can't count on the sorting being the same every time you access the dictionary. However if you wanted to print the keys there a couple of ways to it:

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

    This method uses tuple assignment to access the key and the value. This handy if you need to access both the key and the value for some reason.

    for key in prices.keys():
        print(key)
    

    This will only gives access to the keys as the keys() method implies.

提交回复
热议问题