How do you find the first key in a dictionary?

前端 未结 12 874
清酒与你
清酒与你 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:38

    On a Python version where dicts actually are ordered, you can do

    my_dict = {'foo': 'bar', 'spam': 'eggs'}
    next(iter(my_dict)) # outputs 'foo'
    

    For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.

    For earlier Python versions, there is no "first key".

提交回复
热议问题