[Tutor] Getting first item in dictionary
Joel Goldstick
joel.goldstick at gmail.com
Mon Jan 27 10:14:34 EST 2020
On Mon, Jan 27, 2020 at 10:07 AM Mats Wichmann <mats at wichmann.us> wrote:
>
> On 1/27/20 4:51 AM, 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".
> >
> > 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'}}
> > ```
>
>
> Two simple ways:
>
> >>> d = {'key': 'value'}
>
> 1. use the dict's get method, which returns None if not found:
>
> >>> v = d.get('key')
> >>> print(v)
> value
> >>> v = d.get('foo')
> >>> print(v)
> None
> >>>
>
> 2. use a try/except:
>
> >>> for k in ('key', 'foo'):
> ... try:
> ... print(d[k])
> ... except KeyError:
> ... print("No such key:", k)
> ...
> value
> No such key: foo
> >>>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
Try d.values()
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'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'}}
>>> d
{'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'}}
>>> d.values()
dict_values([{'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'}])
--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
More information about the Tutor
mailing list