首页 > 解决方案 > 如果存在键或默认值,则过滤数组并返回值

问题描述

是否可以过滤特定键值的数组并返回该键的值?

我有以下数组:

[
    {
        "action_type": "landing_page_view",
        "value": "72"
    },
    {
        "action_type": "link_click",
        "value": "6"
    }        
]

action_type: link_click如果此 action_type 不存在,我如何获取值并返回 0?

编辑:我想避免大循环。

标签: python

解决方案


当然,您可以使用过滤器内置功能。

它需要一个 lambda 函数。在这种情况下,它将类似于

lambda x: x['action_type'] == "link_click"

并将结果转换为列表:

dt = [{'action_type': 'landing_page_view', 'value': '72'},
      {'action_type': 'link_click', 'value': '6'}]

list (filter (lambda x: x['action_type'] == "link_click", dt))                            
# Returns [{'action_type': 'link_click', 'value': '6'}]

如果没有找到,它将返回一个空列表。

如果没有找到任何东西,则返回 0 之后非常简单。

# data - the input data
# key - the key to search
# val - the value to compare with
# key2 - the key whose value should be returned in case of a match
def flt (data, key, val, key2):
    found = list (filter (lambda x: x[key] == val, data))
    if found:
        return found[0][key2]
    return 0

为了使它更时尚,使用next@alain-t 建议的功能。

def flt (data, key, val, key2): 
    return next (filter (lambda x: x[key] == val, data), {key2: 0})[key2] 

推荐阅读