简体   繁体   English

如何在字典中找到Y等于Z的X

[英]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.

相关问题 如何从三个数组创建x,y,z坐标,其中x和y是使用meshgrid生成的,而z取决于x? - How do I create x,y,z coordinates from three arrays, where x and y are generated with meshgrid and z is dependent on x? 如何在 8.22 范围内为变量 x 找到一组整数 y、z? - How find a set of integers y, z in the range 8.22 for the variable x? 如何绘制来自3个不同列表(x,y和z)的3d直方图,其中z是所有重复的x,y坐标的平均值 - How to plot a 3d histogram from 3 different lists (x, y and z), where z is the mean of all repeated x,y coordinates FInd(X,Y)对和关联的Z坐标 - FInd (X, Y) pairs and associated Z coordinates 找到 y 最小的 x - Find x where y is minimum matplotlib(等单位长度):具有“等”纵横比z轴不等于x-和y- - matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y- 将 y 的实例更改为 x 中的 z(其中 x 是一个列表) - Change instance of y to z in x(where x is a list) 在回归曲面Z中,如何查找Z小于预定义值的最大X值? - In a regression surface Z, how to find maximum X value where Z is less than a predefined value? 如何组合 x、y 和 z 的单独矩阵? - How to combine separate matrix of x, y and z? 数据结构可以执行“选择不同的X,其中W = w和Y = y,Z = z和…”类型查找 - data structure that can do a “select distinct X where W=w and Y=y and Z=z and …” type lookup
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM