[Tutor] Getting first item in dictionary

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jan 27 13:16:55 EST 2020


On 27/01/2020 11:51, S D wrote:
> 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".

That doesn't make much sense. If you cannot use a key to
access the data why did you put it in a dictionary which
is a structure accessed by keys?

When you say the code will break if you use a wrong key
surely all you should get is a Keyerror? And you can avoid
that by using  dict.get(key) which returns None if the key
is not found. (Although using try/except to catch the error
would be better in this scenario because you should want
to know why you have a wrong key and prevent it!

> How can I access the first item in a dictionary without using a key? 

If that's what you really want you should be using a list
instead of a dictionary.

But you can kind of get that by using dict.values() which
gives you back a list of values (actually a fancy type
of structure that acts like a list)




> 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'}}
> ```

Have you considered creating a class?
With that amount of nested dicts etc I'd have thought
a class would be a better fit. Then maybe a list of instances.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list