在python中提取dict列表中给定键值对的键值
我有一个字典列表,看起来像在python中提取dict列表中给定键值对的键值,python,json,list,dictionary,Python,Json,List,Dictionary,我有一个字典列表,看起来像 [ { "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",
[
{
"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)的设备ID吗
我尝试过将它转换成熊猫数据帧,并尝试使用一些操作进行提取,是否有可能以一种更具python风格的方式进行提取
谢谢。当地板等于
L2
时,您可以迭代并获取设备ID
>>> res = next((d['deviceId'] for d in l if d['floor']=='L2'), None)
>>> res
'fd00::212:4b00:1957:d1a3'
如果我没弄错的话,你想提取地板上的设备ID。您可以使用以下选项:
result = []
for key,data in devices.items():
if data.floor=="L2":
result.append(data.deviceId)
Now the result contain, all ids in floor
<>但您确实应该考虑用不同的方式存储Davice ID。
我希望这有助于您使用与@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']
据我所知,当使用循环和条件组合使用列表时,列表理解是获得所需结果的最有吸引力的方式。大多数情况下,它们比任何其他解决方案都更快、代码更短、更易于阅读。我知道
l
是我的列表。下一步怎么办?我是你的名单。res将从迭代器中获得下一项,如果没有字典有下限L2,那么res将没有。这是否回答了您的问题?