根据一对键值对字典列表排序



列表中的字典之一是:

[{' School': 'GP',
'Age': '18',
'StudyTime': '2',
'Failures': '0',
'Health': '3',
'Absences': '6',
'G1': '5',
'G2': '6',
'G3': '6'}
………………….]

我想按Age排序,所以输出应该是这样的:

Range for age is 15 to 22
{ 15 : [
{'School': 'GP',
'StudyTime': 4.2,
'Failures': 3,
'Health': 3,
'Absences': 6,
'G1': 7,
'G2': 8,
'G3': 10
},
{ ...
other dictionary
},
...
],
16 : [
{'School': 'MS',
'StudyTime': 1,
'Failures': 1.2,
'Health': 4,
'Absences': 10,
'G1': 9,
'G2': 11,
'G3': 7
},
{ ...
other dictionary
},
...
],
...
}

我已经尝试用下面的代码来解决这个问题,但是age_list的索引超出了范围:

age_list = [15,16,17,18,19,20,21,22]
#dict_list is the list of dictionaries that need to be sorted
`  res = defaultdict(list)
for i in age_list:
for j in dict_list:
if age_list[i] == j['Age']:
res[i].append(j)`

print(res)

根据预期的输入和输出,似乎涉及三个任务:

  1. 数字字符串应尽可能转换为整数(例如,"15"应转换为15)。
  2. 字典条目应根据"Age"键进行整理。
  3. 在排序结果中,每个条目应该不再具有"Age"键。

下面是接收单个字典条目并执行第一个任务的函数。

def process_dictionary(dictionary):
result = {}
for key, value in dictionary.items():
# might want to use .isnumeric or .isdecimal instead
if value.isdigit():
result[key] = int(value)
return result

第二个和第三个任务可以通过稍微修改原始代码来实现。

from collections import defaultdict
def collate_by_age(entries):
result = defaultdict(list)
for entry in entries:
# pop (remove) "Age" key from entry
age = entry.pop("Age")
# append to result
result[age].append(entry)
return result

把这些放在一起,

entries = [process_dictionary(dictionary) for dictionary in dictionaries]
result = collate_by_age(entries)

如果你只对一组特定的年龄感兴趣,例如,从15岁到22岁,你可以简单地遍历result字典。

target_age = {age: result[age] for age in range(15, 23)}

最新更新