如何将值附加到字典并对其进行排序?

时间:2019-03-13 04:13:50

标签: python dictionary

我有一个数据结构

Age, Height

它们是数字,将被插入循环中。例如,

dict={}
for i in range (100):
    age= np.random.randint(1,100)
    height= np.random.randint(1,100)
    dict['Age']=age
    dict['Height']=height

经过100次迭代后,我希望输出结果会喜欢

Age, Height
10, 20
2, 10
23, 14
....

在那之后,我想通过降低年龄来对结果进行排序,字典会很喜欢

Age, Height
23,14
10,20
2,10

在这种情况下,我应该在python中使用字典吗?我还想获得2个年龄最大的职位,例如23,14和10,20。怎么做?谢谢

3 个答案:

答案 0 :(得分:3)

您应该将结果添加到列表中,而不是dic

import random

my_list=[]
for i in range(100):
    age = random.randint(1, 100)
    height = random.randint(1, 100)
    my_list.append({"Age": age, "Height": height})

然后可以使用Python的sorted()函数和 reverse=True 自变量

进行排序
sorted_list = sorted(my_list,key=lambda x:x['Age'],reverse=True)

答案 1 :(得分:2)

看起来像是您想要的字典列表,而不是字典。示例:

my_list = []
for in in range(100):
    age= np.random.randint(1,100)
    height= np.random.randint(1,100)
    my_list.append({'Age': age, 'Height': height})

然后,您可以输出它们:

print('Age, Height')
for elem in my_list:
    print('{}, {}'.format(elem['Age'], elem['Height']))

并对它们进行排序(反向):

my_list.sort(key=lambda x: -1 * x['Age'])

答案 2 :(得分:1)

使用字典实现时,最后只会加上最后的squeezeage,所有其他的都将被覆盖。也许列出一个键值可以节省您的时间。

这使用height创建带有值列表的字典,并使用collections.defauldict对它们进行排序:

zip

现在您有了排序的结果,请遍历它们:

import numpy as np
from collections import defaultdict

d = defaultdict(list)

for _ in range (100):
    age = np.random.randint(1,100)
    height = np.random.randint(1,100)
    d['Age'].append(age)
    d['Height'].append(height)

print(d)

vals = list(d.values())
sorted_values = sorted(zip(vals[0], vals[1]), key=lambda x: x[0], reverse=True)