简体   繁体   English

Python-从字典中获取有序键/值对的最简单方法?

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

I have the following dictionary, age_freq: 我有以下字典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 Python的字典未排序,因此iteritems()将以与以前相同的“顺序”返回键和值

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. 因为这样会在最后一键弹出键,所以您将得到一个空字典,但是如果您只是创建一个饼图,那就没关系了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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