Python 如何访问列表中的词典

Python 如何访问列表中的词典,python,list,dictionary,Python,List,Dictionary,如何同时访问“x”和“y”,以计算具有以下内容的词典列表中连续术语之间的差异 data_points = [{ "y": 621, "x": 399, "time ns": 107353592, "time ms": 1529423113, "cameraID": 0 }, { "y": 621, "x": 399, "time ns": 111057583, "time ms": 15294231

如何同时访问“x”和“y”,以计算具有以下内容的词典列表中连续术语之间的差异

data_points = [{ "y": 621, "x": 399, "time ns": 107353592,
                 "time ms": 1529423113, "cameraID": 0 },
               { "y": 621, "x": 399, "time ns": 111057583,
                 "time ms": 1529423113, "cameraID": 0 },
               { "y": 621, "x": 399, "time ns": 114741998,
                 "time ms": 1529423113, "cameraID": 0 },
               { "y": 621, "x": 399, "time ns": 118388882,
                 "time ms": 1529423113, "cameraID": 0 }
              ]
我试过了,但没有成功

data_points[0]['x']['y']

不幸的是,您不能用这种语法一次访问多个字典键,但是您可以用列表理解轻松地做到这一点。例如,要从列表的第一个字典中获取
x
y
,可以执行以下操作:

[data_points[0][i] for i in ['x', 'y']]
要获得:

[399, 621]

不幸的是,您不能用这种语法一次访问多个字典键,但是您可以用列表理解轻松地做到这一点。例如,要从列表的第一个字典中获取
x
y
,可以执行以下操作:

[data_points[0][i] for i in ['x', 'y']]
要获得:

[399, 621]
我想你想要这个:

abs(data_points[0]['x']-data_points[0]['y'])
我想你想要这个:

abs(data_points[0]['x']-data_points[0]['y'])

使用
操作符.itemgetter

from operator import itemgetter

res = itemgetter('x', 'y')(data_points[0])

(399, 621)

使用
操作符.itemgetter

from operator import itemgetter

res = itemgetter('x', 'y')(data_points[0])

(399, 621)
如果要比较两者,请执行以下操作:

if accessX and accessY == "something like this":
     #then do whatever you want
现在,您可以在一个字符串中访问这两个词,然后只需使用
split()
方法,选择您想要的单词

如果要比较两者,请执行以下操作:

if accessX and accessY == "something like this":
     #then do whatever you want

现在您可以在一个字符串中访问这两个键,然后只需使用
split()
方法,选择您想要的单词。

data\u points[0]['x']['y']将返回错误,因为您的意思是,x中有另一个称为y的键,并且您正在尝试访问不存在data\u points[0]['x']['y']将返回错误,因为您说在x中有另一个名为y的键,并且您正在尝试访问不存在的值