[英]How to find X where Y is equal to Z in dictionary
In javascript, one can use "find" or "findIndex" to extract the object { "src": "findThis", "type": "the right one" }
from在 javascript 中,可以使用“find”或“findIndex { "src": "findThis", "type": "the right one" }
从
{ "results": [
{ "src": "findThat", "type": "not the right one" },
{ "src": "findThis", "type": "the right one" }
]
}
How would i do this in python?我将如何在 python 中执行此操作?
This is a bit unclear as to what the actual data structure looks like in Python.这有点不清楚 Python 中的实际数据结构是什么样的。 Based on the example as written I'm assuming you have an array of dictionaries.根据所写的示例,我假设您有一系列字典。
data = [{"src": "findThat", "type": "not the right one" },
{ "src": "findThis", "type": "the right one" }]
In this case you can use a loop, but it is more "pythonic" to use a comprehension.在这种情况下,您可以使用循环,但使用理解更“pythonic”。
filtered = [a for a in data if a["src"] == "findThis"]
Or more generically,或者更一般地说,
key, value = "src", "find this"
filtered = [a for a in data if a[key] == value]
You could also use the filter
function with a lambda function but adding that complexity seems unnecessary here.您也可以将filter
function 与 lambda function 一起使用,但在这里添加复杂性似乎是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.