python - 如果存在键或默认值,则过滤数组并返回值
问题描述
是否可以过滤特定键值的数组并返回该键的值?
我有以下数组:
[
{
"action_type": "landing_page_view",
"value": "72"
},
{
"action_type": "link_click",
"value": "6"
}
]
action_type: link_click
如果此 action_type 不存在,我如何获取值并返回 0?
编辑:我想避免大循环。
解决方案
当然,您可以使用过滤器内置功能。
它需要一个 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]
推荐阅读
- ruby-on-rails - Michael Hartl - 第 6 章 - 用户类变为 nil 并为 nil:NilClass 抛出未定义的方法 `authenticate'
- c# - 如何使字段 text_ws 不区分大小写
- java - 在项目资源管理器中选择文件时编辑器未激活
- php - 图像“http://localhost/KVL/showgraph”无法显示,因为它包含错误 - Jpgraph
- sql - .sql Dump Import with ERROR 1064 (42000) near '*/' at line 1
- javascript - 从具有自定义属性的json加载对象后,如何在fabric js 1.7.22版中创建对象组?
- java - 在 JDialog 中创建条件
- java - SPRING/THYMELEAF:如何在表格中填写列表并将另一行附加到表格中?
- r - 将动态子集条件作为变量添加到 data.frame
- python - Django:在其他应用程序中使用 ImageFields?