在python中使用多个值从dict键返回一个值

时间:2014-01-11 06:38:02

标签: python dictionary

我试图从以下词典中返回“runnerName”:

{u'marketId': u'1.112422365',
 u'marketName': u'1m Mdn Stks',
 u'runners': [{u'handicap': 0.0,
               u'runnerName': u'La Napoule',
               u'selectionId': 8095372,
               u'sortPriority': 1},
              {u'handicap': 0.0,
               u'runnerName': u'Swivel',
               u'selectionId': 701378,
               u'sortPriority': 2},
              {u'handicap': 0.0,
               u'runnerName': u'Deanos Devil',
               u'selectionId': 8100420,
               u'sortPriority': 3},
              {u'handicap': 0.0,
               u'runnerName': u'Bishan Bedi',
               u'selectionId': 8084336,
               u'sortPriority': 4},
              {u'handicap': 0.0,
               u'runnerName': u'In Seine',
               u'selectionId': 8199415,
               u'sortPriority': 5},
              {u'handicap': 0.0,
               u'runnerName': u'Needs The Run',
               u'selectionId': 8199416,
               u'sortPriority': 6},
              {u'handicap': 0.0,
               u'runnerName': u'Appellez Baileys',
               u'selectionId': 8148513,
               u'sortPriority': 7},
              {u'handicap': 0.0,
               u'runnerName': u'Jessy Mae',
               u'selectionId': 7652545,
               u'sortPriority': 8},
              {u'handicap': 0.0,
               u'runnerName': u'Redy To Rumble',
               u'selectionId': 7366163,
               u'sortPriority': 9}]}

我尝试了很多不同的方法,但无法弄清楚如何从具有多个值的键中访问值。

1 个答案:

答案 0 :(得分:6)

  1. 您可以使用列表推导(如此)从跑步者词典中检索跑步者名称。

    print [runner["runnerName"] for runner in runners_dict["runners"]]
    
  2. 或者您可以使用operator.itemgetter,就像这样

    from operator import itemgetter
    print map(itemgetter("runnerName"), runners_dict["runners"])
    
  3. <强>输出

    [u'La Napoule', u'Swivel', u'Deanos Devil', u'Bishan Bedi', u'In Seine',
     u'Needs The Run', u'Appellez Baileys', u'Jessy Mae', u'Redy To Rumble']
    
相关问题