我有以下字典串列,以及子字典資料:
data2 = [
{"dep": None},
{"dep": {
"eid": "b3ca7ddc-0d0b-4932-816b-e74040a770ec",
"nid": "fae15b05-e869-4403-ae80-6e8892a9dbde",
}
},
{"dep": None},
{"dep": {
"eid": "c3bcaef7-e3b0-40b6-8ad6-cbdb35cd18ed",
"nid": "6a79c93f-286c-4133-b620-66d35389480f",
}
},
]
我有一個匹配鍵:
match_key = "b3ca7ddc-0d0b-4932-816b-e74040a770ec"
我想看看data2中每個“dep”鍵的任何子詞典是否有一個與我的match_key匹配的eid。我正在嘗試以下操作,但我得到一個 TypeError: string indices must be integers - 我哪里出錯了?
我的代碼
matches = [
d["eid"]
for item in data2
if item["dep"]
for d in item["dep"]
if d["eid"] == match_key
]
所以比賽應該回傳:
["b3ca7ddc-0d0b-4932-816b-e74040a770ec"]
這意味著它在 data2 中找到了這個 id。
uj5u.com熱心網友回復:
當您遍歷字典時,每次迭代都會為您提供字典中的一個鍵。
d["eid"]實際上也是如此"eid"["eid"],這是一個無效的運算式。這就是 Python 引發以下例外的原因:
TypeError:字串索引必須是整數
此外,該運算式d["eid"]假定 eachd包含eid密鑰。如果沒有,Python 將引發一個KeyError.
如果您不確定“eid”是否是字典中的有效鍵,請改用該.get方法。
matches = [
v
for item in data2
if item.get("dep") # Is there a key called dep, and it has a non-falsy value in it
for k, v in item["dep"].items() # Iterate over the dictionary items
if k == "eid" and v == match_key
]
您可以通過直接訪問鍵的值來做得更好eid:
matches = [
d["dep"]["eid"]
for d in data2
if d.get("dep") and d["dep"].get("eid") == match_key
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484621.html
標籤:python-3.x 字典
