简体   繁体   中英

Python - Easiest way to get ordered key/value pairs from dictionary?

I have the following dictionary, age_freq:

age_freq = {'Age35-44': 194, 'Age0-14': 11, 'Age55-64': 51, 'Age45-54': 142, 'Age65-74': 12, 'Age15-24': 223, 'Age25-34': 310}

I want to return the key/value pairs from this dictionary for the purposes of creating a pie chart. My code to do this is below:

age_range=[]
freq=[]

for key, value in age_freq.iteritems():
    aKey = key
    aValue = value
    age_range.append(aKey)
    freq.append(aValue)

This works fine and I get the following two lists:

age_range = ['Age35-44', 'Age0-14', 'Age65-74', 'Age45-54', 'Age55-64', 'Age15-24', 'Age25-34']

freq = [194, 11, 12, 142, 51, 223, 310]

However I want the lists to be ordered by increasing age range. What is the easiest way to do this?

Just sort it.

age_range, freq = zip(*sorted(age_freq.items()))

If the age ranges were less tidy, as mentioned in comments, you could explicitly extract them, with (for example) turning the low and high end of each range into an integer and then finding their average:

age_range, freq = zip(*sorted(age_freq.items(), key=lambda x: (int(x[3].split('-')[0]) + int(x[3].split('-')[1]) / 2))

我相信最Python化的方式是:

sortedFreq = [(key, age_freq[key]) for key in sorted(age_freq)]

I don't know if it's very tidy and efficient but I think sometimes readability/reusability counts so I suggest converting it to a list of dictionaries:

age_freq = {'Age35-44': 194, 'Age0-14': 11, 'Age55-64': 51, 'Age45-54': 142, 'Age65-74': 12, 'Age15-24': 223, 'Age25-34': 310}

table = [{'start': int(key.split('Age')[1].split('-')[0]),
          'stop': int(key.split('Age')[1].split('-')[1]),
          'freq': age_freq[key]}
         for key in age_freq]

and now you can do whatever you like with it: Sort by start-age

import operator
sorted(table, key=operator.itemgetter('start'))

Sort by stop-age

sorted(table, key=operator.itemgetter('start'))

Sort by frequency

sorted(table, key=operator.itemgetter('freq'))

but thats probably not the "easiest" way.

Python's dictionaries are not ordered, so iteritems() will return the keys and values in the same 'order' as before

To create ordered key/value lists you can do something like this:

for key in sorted(age_freq.keys()):
    aKey = key
    aValue = age_freq.pop(key)

    age_range.append(aKey)
    freq.append(aValue)

Since this pops the keys out one by one at the end you'll be left with an empty dictionary, but if you're just creating a pie chart it shouldn't matter.

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