簡體   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