【发布时间】:2020-06-19 07:25:53
【问题描述】:
x = {'Jackie': 176, 'Wilson': 185, 'Saersha': 165,'Roman': 185,'Abram': 169}
y = [(v, k) for k, v in x.items()] # creates a list of tuples as (value, key) pair
y.sort(reverse = True) # sorts the items in a list
# creates a dictionary with key as value from list(x) and value as a list of key from list(x)
z = {}
for a in y:
if a[0] in z:
z[a[0]].append(a[1])
else:
z[a[0]] = [a[1]]
print(z)
输出不应该是:
{185: ['Wilson', 'Roman'], 176: ['Jackie'], 169: ['Abram'], 165: ['Saersha']}
相反,它是这样的:
{176: ['Jackie'], 185: ['Wilson', 'Roman'], 165: ['Saersha'], 169: ['Abram']}
【问题讨论】:
-
确定吗?不是当我执行它时......
-
顺便检查一下 defaultdicts 这样的用例。
-
为什么重要?在字典中排序不是问题。
标签: python dictionary tuples