How do you find the first key in a dictionary?

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

    For Python 3 below eliminates overhead of list conversion:

    first = next(iter(prices.values()))
    
    0 讨论(0)
  • 2020-11-27 11:31

    The dict type is an unordered mapping, so there is no such thing as a "first" element.

    What you want is probably collections.OrderedDict.

    0 讨论(0)
  • 2020-11-27 11:35

    d.keys()[0] to get the individual key.

    Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections

    prices  = collections.OrderedDict((
    
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),
    ))
    prices.keys()[0]
    

    'banana'

    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2020-11-27 11:38

    easiest way is:

    first_key = my_dict.keys()[0]
    

    but some times you should be more careful and assure that your entity is a valuable list so:

    first_key = list(my_dict.keys())[0]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题