【问题标题】:Return ordered subset of values from dictionary从字典中返回有序的值子集
【发布时间】:2020-03-13 19:41:15
【问题描述】:

我有这本词典

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

【问题讨论】:

  • 你试过什么?什么不起作用? SO 不是代码工厂,您可以在其中要求人们编写您的代码...

标签: python string list sorting dictionary


【解决方案1】:

可以这样做:

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']])

【讨论】:

    【解决方案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 name in sorted([person['name'] for person in d['people']]):
      print(name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 2011-07-18
      相关资源
      最近更新 更多