[英]Extract vale of a key for a given key value pair in a list of dict in python
I have a list of dictionary which looks like.我有一个看起来像的字典列表。
[
{
"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"
}
]
Can somone help me with how do I extract the deviceId of a given floor like L2?有人可以帮助我如何提取给定楼层(如 L2)的 deviceId 吗?
I have tried converting it into a pandas dataframe and trying to extract using some operations, is it possible to do it in a more pythonic way.我已经尝试将它转换为熊猫数据帧并尝试使用一些操作进行提取,是否可以以更 Pythonic 的方式进行。
Thanks.谢谢。
You can iterate and get the deviceId
when floor is equal to L2
.当 floor 等于
L2
时,您可以迭代并获取deviceId
。
>>> res = next((d['deviceId'] for d in l if d['floor']=='L2'), None)
>>> res
'fd00::212:4b00:1957:d1a3'
If i understand the question right, you want to extract deviceId's that are on floor.如果我理解正确,您想提取地板上的 deviceId。 You can use this:
你可以使用这个:
result = []
for key,data in devices.items():
if data.floor=="L2":
result.append(data.deviceId)
Now the result contain, all ids in floor
But you should really consider storing deviceId's for floors in different way.但是您真的应该考虑以不同的方式存储楼层的 deviceId。
I hope this helped you我希望这对你有帮助
Same logic as the one from @Jiri Otuupal, but in a more compact form using list comprehension:与@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']
OUTPUT输出
print(res)
# ['fd00::212:4b00:1957:d1a3']
To the best of my knowledge, when working with lists in combinations with loops and conditions, list comprehensions are the most pythonic way of getting the desired result.据我所知,在将列表与循环和条件结合使用时,列表推导式是获得所需结果的最 Python 化的方式。 Most of the times they are faster, shorter in code and easier to read than any other solutions.
大多数情况下,它们比任何其他解决方案更快、代码更短且更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.