[Tutor] Getting first item in dictionary

Roel Schroeven roel at roelschroeven.net
Mon Jan 27 14:30:09 EST 2020


S D schreef op 27/01/2020 om 12:51:
> I have a dictionary which contains one item (“current_location”, which is a
> nested dict) and I would like to access that nested dict. However, I cannot
> use the key as the code will break if a different key is passed, e.g.
> “different_location".
> 
> How can I access the first item in a dictionary without using a key? The
> dict looks like this:
> 
> ```
> {'current_location': {'date': '2020-01-27T10:28:24.148Z', 'type_icon':
> 'partly-cloudy-day', 'description': 'Mostly Cloudy', 'temperature': 68.28,
> 'wind': {'speed': 10.48, 'bearing': 178, 'gust': 12.47}, 'rain_prob': 0.02,
> 'latitude': '-33.927407', 'longitude': '18.415747', 'request_id': 31364,
> 'request_location': 'Current location'}}
> ```

If you are really sure that there is only one item in the dictionary, 
you can simply retrieve the first value without even looking at the key:

from pprint import pprint
loc_dict = {'current_location': {'date': '2020-01-27T10:28:24.148Z',
                       'description': 'Mostly Cloudy',
                       'latitude': '-33.927407',
                       'longitude': '18.415747',
                       'rain_prob': 0.02,
                       'request_id': 31364,
                       'request_location': 'Current location',
                       'temperature': 68.28,
                       'type_icon': 'partly-cloudy-day',
                       'wind': {'bearing': 178,
                                'gust': 12.47,
                                'speed': 10.48}}}
first_value = list(loc_dict.values())[0]
pprint(first_value)

Outputs:

{'date': '2020-01-27T10:28:24.148Z',
  'description': 'Mostly Cloudy',
  'latitude': '-33.927407',
  'longitude': '18.415747',
  'rain_prob': 0.02,
  'request_id': 31364,
  'request_location': 'Current location',
  'temperature': 68.28,
  'type_icon': 'partly-cloudy-day',
  'wind': {'bearing': 178, 'gust': 12.47, 'speed': 10.48}}


That should extract the one item from a dictionary, if there is only 
one. And I think it should extract the first item even if there are 
multiple items, but that "first item" might not be what you expect 
depending on your expectations and the version of Python you use.


-- 
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
         -- Franklin P. Jones

Roel Schroeven



More information about the Tutor mailing list