繁体   English   中英

在python中的dict列表中提取给定键值对的键值

[英]Extract vale of a key for a given key value pair in a list of dict in python

我有一个看起来像的字典列表。

[
  {
    "deviceId": "d61e",
    "floor": "L1",
    "id": "l1-topic"
  },
  {
    "deviceId": "fd00::212:4b00:1957:d197",
    "floor": "L3",
    "id": "l3-topic"
  },
  {
    "deviceId": "fd00::212:4b00:1957:d1a3",
    "floor": "L2",
    "id": "l2-topic"
  }
]

有人可以帮助我如何提取给定楼层(如 L2)的 deviceId 吗?

我已经尝试将它转换为熊猫数据帧并尝试使用一些操作进行提取,是否可以以更 Pythonic 的方式进行。

谢谢。

当 floor 等于L2时,您可以迭代并获取deviceId

>>> res = next((d['deviceId'] for d in l if d['floor']=='L2'), None)
>>> res
'fd00::212:4b00:1957:d1a3'

如果我理解正确,您想提取地板上的 deviceId。 你可以使用这个:

result = []
for key,data in devices.items():
    if data.floor=="L2":
       result.append(data.deviceId)

Now the result contain, all ids in floor

但是您真的应该考虑以不同的方式存储楼层的 deviceId。

我希望这对你有帮助

与@Jiri Otuupal 的逻辑相同,但使用列表理解以更紧凑的形式:

# I assume the given list is stored in a variable called "dicts"
res = [d['deviceId'] for d in dicts if d['floor'] == 'L2']

输出

print(res)
# ['fd00::212:4b00:1957:d1a3'] 

据我所知,在将列表与循环和条件结合使用时,列表推导式是获得所需结果的最 Python 化的方式。 大多数情况下,它们比任何其他解决方案更快、代码更短且更易于阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM