简体   繁体   中英

python - Converting python dictionary values to respective key-value pairs

Currently I am working with Django querysets and am getting a result like this:

[{'week': 29, 'avg': 137.6}, {'week': 30, 'avg': 138.6}, {'week': 31, 'avg': 138.06666666666666}]

As you can see, its a list of dictionaries.

I want to deal with simply:

{29: 137.6, 30: 138.6, 31: 138.066}

I'm having some trouble looping my head through all this. Any help would be appreciated. Thank you.

Simply use dictionary comprehension :

{ d['week'] : d['avg'] for d in data }

Where data is your list of dictionaries. This produces:

>>> { d['week'] : d['avg'] for d in data }
{29: 137.6, 30: 138.6, 31: 138.06666666666666}

The dictionary comprehension will thus iterate through data , and for every element d (a dictionary), it will associate d['week'] (key) with d['avg'] (value) in the result.

In case it is not a list of dictionaries, but still a queryset, you should - like @JonClemens says - use the following expression:

dict(queryset.values_list('week','avg'))

Here values_list('week','avg') will construct an iterable of 2-tuples that contain the week as first element, and the average as second element. If the dict(..) constructor obtains an iterable of 2-tuples, it will construct a dictionary where the first element of every tuple is the key, and the second element of the tuple the associated value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM