Getting the first item in a dict

22 просмотра
Перейти к первому непрочитанному сообщению

S D

не прочитано,
27 янв. 2020 г., 06:58:1827.01.2020
– django...@googlegroups.com
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'}}
`

Kind regards,
- SD

Mike Dewhirst

не прочитано,
27 янв. 2020 г., 07:33:2627.01.2020
– django...@googlegroups.com
Can you use ddict[ddict.keys()[0]] ???

I don't know if that would show you the first item unless it was an ordered dict. 

Mike
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAH-SnCBnnOsoTURnSzCrqqXsCWF5EEjghm9Q1UTQKrnTBAJ3iA%40mail.gmail.com.

Nick Sarbicki

не прочитано,
27 янв. 2020 г., 07:40:3927.01.2020
– Django users
I think the real question here is why you have a dict with one item in it?

If you can construct it so that this isn't the case that would be ideal.

If you really can't construct it any other way then you can do something simple like my_dict.popitem()[1] to get the value of the only item in the dict. Although it is worth noting this will also remove that item from the dict (giving you a single non-nested dict which seems more desirable).


- Nick


Bill Freeman

не прочитано,
27 янв. 2020 г., 07:51:5627.01.2020
– django-users
Note that these give the only value.  This won't work if you have more than one value in the dict, since you won't know which you will get.  Where d is the dict:

    list(d.values())[0]

or

    for i in d.values():
        # use i here
        print(i)

or

    d[list(d)[0]]

I'm sure that there are other ways.  There is certainly at least a way to play with the iterator protocol without using "for", but it may be harder to read.  You could put break at the end of the loop above to make it more apparent that it only runs once.

--

S D

не прочитано,
27 янв. 2020 г., 08:17:3627.01.2020
– django...@googlegroups.com
I ended up using `dict[next(iter(dict))]`

I am getting the dict as one of two dicts nested in a list from a weather service API. I do this using a list comprehension to call the API with coordinates for each location in another list. A mouthful.

`resp = [fetch_api_data(location, request_id) for location in REQUEST_LOCATIONS]`

I then cycle through the list and, for each dict, persist a WeatherRequest instance to db like so:

`
for item in weather_data:
data = item[next(iter(item))]
WeatherRequest(
date=data['date'],
request_id=data['request_id'],
request_location=data['request_location'],
type_icon=data['type_icon'],
description=data['description'],
temperature=data['temperature'],
wind_speed=data['wind']['speed'],
wind_bearing=data['wind']['bearing'],
wind_gust=data['wind']['gust'],
rain_prob=data['rain_prob'],
latitude=data['latitude'],
longitude=data['longitude']
).save()
`

Thanks.


Kind regards,
- SD


Ответить всем
Отправить сообщение автору
Переслать
0 новых сообщений