【问题标题】:Search for value in a key from list of dictionaries and return a different key value从字典列表中搜索键中的值并返回不同的键值
【发布时间】:2011-08-16 16:29:50
【问题描述】:

继续stackoverflow question。 我有以下数据结构:

data = [
  {'site': 'Stackoverflow', 'id': 1},
  {'site': 'Superuser', 'id': 2}, 
  {'site': 'Serverfault', 'id': 3}
]

我想在所有“站点”键中搜索特定值,并返回该字典的“id”值。例如,搜索“超级用户”应该返回 2:

>>> print find_id('Superuser')
2

当我尝试使用引用问题的解决方案时,我收到了一个错误:

>>> if any(d['site'] == 'Superuser' for d in data): print d['Superuser']
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> if any(d['site'] == 'Superuser' for d in data): print data['Superuser']
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

最pythonic的方式是什么?

【问题讨论】:

  • def find_id(data, name): return next((d['id'] for d in data if d['site'] == name), None)

标签: python list search dictionary key


【解决方案1】:

这里没有技巧。做吧:

def find_id(data, name):
    for d in data:
        if d['site'] == name:
            return d['id'] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多