dicts_lists = [
{
“Name”: “James”,
“Age”: 20,
},
{
“Name”: “May”,
“Age”: 14,
},
{
“Name”: “Katy”,
“Age”: 23,
}
]
方法一
dicts_lists.sort(key=lambda item: item.get(“Age”))
方法二
from operator import itemgetter
f = itemgetter(‘Name’)
dicts_lists.sort(key=f)
(涉及到字典排序的)一道牛客网上的编程题
n = int(input())
d = dict()
for i in range(n):
k, v = input().split(' ')
# 注意,这里必须要转为int类型,不然sorted()函数会按照ascii码进行排序,不对题意
k = int(k)
v = int(v)
if k in d:
d[k] += int(v)
else:
d[k] = int(v)
d = {i: d[i] for i in sorted(d)}
for k, v in d.items():
print(k, v)