从词典列表中获取最高薪水前三名

问题描述 投票:0回答:1

薪资最高前三名

sample_list = [

{'name': 'John', 'salary': 6000},

{'name': 'Jane', 'salary': 8000},

{'name': 'Tom', 'salary': 7500},

{'name': 'Emma', 'salary': 8000},

{'name': 'Emily', 'salary': 3000},

{'name': 'Dan', 'salary': 500},

{'name': 'Brad', 'salary': 400}

]

top_three_employees = 3

expected_output = ['Jane', 'Tom', 'Emma'\]
python list dictionary max
1个回答
0
投票

使用

sorted
方法获取按工资顺序排列的数据,这很容易实现。然后,您只需迭代它并选择前三个条目的名称即可。

例如

sample_list = [
    {'name': 'John', 'salary': 6000},
    {'name': 'Jane', 'salary': 8000},
    {'name': 'Tom', 'salary': 7500},
    {'name': 'Emma', 'salary': 8000},
    {'name': 'Emily', 'salary': 3000},
    {'name': 'Dan', 'salary': 500},
    {'name': 'Brad', 'salary': 400}
]

# Sorting the list of dictionaries by 'salary' in descending order
sorted_list = sorted(sample_list, key=lambda x: x['salary'], reverse=True)

# Getting the names of the top 3 earners
top_3_names = [entry['name'] for entry in sorted_list[:3]]

print(top_3_names)
© www.soinside.com 2019 - 2024. All rights reserved.