我的字典中有這個問題我有這個串列:
l=['a','b','c']
所以我想將它附加到我的字典串列中
d=[{
"type": "text",
"title": "",
"value": ""
}]
但根據我的第一個串列的長度,它會在“d”內自動創建另一個字典
我的預期輸出:
d=[{
"type": "text",
"title": "a",
"value": "/a"
},
{
"type": "text",
"title": "b",
"value": "/b"
},
{
"type": "text",
"title": "c",
"value": "/c"
}
]
謝謝!!
uj5u.com熱心網友回復:
如果您使用 python ≥ 3.9,您可以在串列理解中使用字典更新運算子 ( ):|
out = [d[0]|{'title': x, 'value': f'/{x}'} for x in l]
輸出:
[{'type': 'text', 'title': 'a', 'value': '/a'},
{'type': 'text', 'title': 'b', 'value': '/b'},
{'type': 'text', 'title': 'c', 'value': '/c'}]
uj5u.com熱心網友回復:
如果鍵是固定的,您可以為串列的每個專案創建一個 dict 專案并將其附加到您的初始 dicts 串列中。像下面這樣的東西會做到這一點。
l=['a','b','c']
d=[{
"type": "text",
"title": "",
"value": ""
}]
for item in l:
dict_item={"type": "text", "title": item, "value": f"/{item}"}
d.append(dict_item)
輸出:
[{'type': 'text', 'title': '', 'value': ''},
{'type': 'text', 'title': 'a', 'value': '/a'},
{'type': 'text', 'title': 'b', 'value': '/b'},
{'type': 'text', 'title': 'c', 'value': '/c'}]
uj5u.com熱心網友回復:
l=['a','b','c']
template = {
"type": "text",
"title": "",
"value": ""
}
d = []
for v in l:
template["title"] = v
template["value"] = "/" v
d.append(dict(template))
事實上,在最后一行中,您不能只附加template,因為它會作為參考附加。在附加模板之前,您必須從模板創建另一個字典。
uj5u.com熱心網友回復:
你可以有一個單一的解決方案
l = ['a','b','c']
d = []
d = d.append([{"type": type(val), "title": val, "value": "/" val} for val in l])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471974.html
