【问题标题】:Get Dictionary value Python获取字典值Python
【发布时间】:2014-01-12 04:43:14
【问题描述】:

我有一个 Python 中的字典列表,我想检查特定术语是否存在字典条目。它使用语法工作

if any(d['acronym'] == 'lol' for d in loaded_data):
       print "found"

但我也想获取存储在此键上的值,我的意思是 d['acronym']['meaning']。我的问题是,当我尝试将其打印出来时,Python 不知道 d。有什么建议,也许我怎样才能在不遍历所有列表的情况下获得出现的索引?谢谢!

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    如果您知道最多有一个匹配项(或者,您只关心第一个匹配项),您可以使用next:

    >>> loaded_data = [{"acronym": "AUP", "meaning": "Always Use Python"}, {"acronym": "GNDN", "meaning": "Goes Nowhere, Does Nothing"}]
    >>> next(d for d in loaded_data if d['acronym'] == 'AUP')
    {'acronym': 'AUP', 'meaning': 'Always Use Python'}
    

    然后取决于您是否想要异常或None 作为未找到的值:

    >>> next(d for d in loaded_data if d['acronym'] == 'AZZ')
    Traceback (most recent call last):
      File "<ipython-input-18-27ec09ac3228>", line 1, in <module>
        next(d for d in loaded_data if d['acronym'] == 'AZZ')
    StopIteration
    
    >>> next((d for d in loaded_data if d['acronym'] == 'AZZ'), None)
    >>> 
    

    如果你愿意,你甚至可以直接获取值而不是字典:

    >>> next((d['meaning'] for d in loaded_data if d['acronym'] == 'GNDN'), None)
    'Goes Nowhere, Does Nothing'
    

    【讨论】:

    • +1 这是一个非常好的方法,可以避免遍历整个列表。
    【解决方案2】:

    你可以使用filter函数:

    filter(lambda d: d['acronym'] == 'lol', loaded_data)
    

    这将返回一个包含acronym == lol的字典列表:

    l = filter(lambda d: d['acronym'] == 'lol', loaded_data)
    if l:
        print "found"
        print l[0]
    

    甚至根本不需要使用any 函数。

    【讨论】:

    • 完美,这正是我想要的!!非常感谢! :)
    • @Crista23 很高兴,我更新了问题,不需要any :)
    • 但是,即使在找到第一个匹配的字典之后,它也会继续循环,这可能无关紧要。
    • 确实如此。 OP没有具体说明。 DSM 的答案使用迭代器涵盖了该部分。
    【解决方案3】:

    如果您想使用该项目,而不仅仅是检查它是否存在:

    for d in loaded_data:
        if d['acronym'] == 'lol':
            print("found")
            # use d
            break # skip the rest of loaded_data
    

    【讨论】:

    • 谢谢,我只是希望有办法避免这些东西! :-)
    • any 检查无论如何都会在幕后执行此操作,因此效率不会降低!
    【解决方案4】:

    any() 只给你一个布尔值,所以你不能使用它。所以只需要写一个循环:

    for d in loaded_data:
        if d['acronym'] == 'lol':
            print "found"
            meaning = d['meaning']
            break
    else:
        # The else: of a for runs only if the loop finished without break
        print "not found"
        meaning = None
    

    编辑:或将其更改为更通用的函数:

    def first(iterable, condition):
        # Return first element of iterable for which condition is True
        for element in iterable:
            if condition(element):
                return element
        return None
    
    found_d = first(loaded_data, lambda d: d['acronym'] == 'lol')
    if found_d:
        print "found"
        # Use found_d
    

    【讨论】:

      【解决方案5】:
      firstone = next((d for d in loaded_data if d['acronym'] == 'lol'), None)
      

      为您提供条件适用的第一个字典,如果没有这样的字典,则为您提供None。

      【讨论】:

        猜你喜欢
        • 2014-06-11
        • 1970-01-01
        • 2018-07-08
        • 2013-07-02
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多