从字典返回值的有序子集

时间:2019-11-18 12:24:26

标签: python

我有这本字典

people = {'people': [{'name': 'Christina Koch', 'craft': 'ISS'}, {'name': 'Alexander Skvortsov', 'craft': 'ISS'}, {'name': 'Luca Parmitano', 'craft': 'ISS'}, {'name': 'Andrew Morgan', 'craft': 'ISS'}, {'name': 'Oleg Skripochka', 'craft': 'ISS'}, {'name': 'Jessica Meir', 'craft': 'ISS'}], 'number': 6, 'message': 'success'}

我只需要获取名称,例如:

    Alexander Skvortsov
    Alexey Ovchinin
    Andrew Morgan
    Christina Koch
    Luca Parmitano
    Nick Hague

谢谢您的帮助

2 个答案:

答案 0 :(得分:2)

可以这样做:

d = {'people': [{'name': 'Christina Koch', 'craft': 'ISS'}, {'name': 'Alexander Skvortsov', 'craft': 'ISS'}, {'name': 'Luca Parmitano', 'craft': 'ISS'}, {'name': 'Andrew Morgan', 'craft': 'ISS'}, {'name': 'Oleg Skripochka', 'craft': 'ISS'}, {'name': 'Jessica Meir', 'craft': 'ISS'}], 'number': 6, 'message': 'success'}

for p in d['people']:
    print(p['name'])

或者如果您希望结果显示在按字母顺序排序的列表中:

name_list = sorted([p['name'] for p in d['people']])

答案 1 :(得分:0)

这应该有效。

d = {'people': [{'name': 'Christina Koch', 'craft': 'ISS'}, {'name': 'Alexander Skvortsov', 'craft': 'ISS'}, {'name': 'Luca Parmitano', 'craft': 'ISS'}, {'name': 'Andrew Morgan', 'craft': 'ISS'}, {'name': 'Oleg Skripochka', 'craft': 'ISS'}, {'name': 'Jessica Meir', 'craft': 'ISS'}], 'number': 6, 'message': 'success'}

for name in sorted([person['name'] for person in d['people']]):
  print(name)