[英]Adding a value to a specific key in a dictionary in Python
我是 Python 的新手。 我正在學習字典。 我想在現有字典中插入一個新值。 現有字典為 d={5:'acb',6:'bhg',7:'cssd'}。 我想在 5 號鍵處添加一個新值“xsd”,但我無法這樣做。 我已經從我身邊嘗試了以下內容。 請幫忙。
d={5:'acb',6:'bhg',7:'cssd'}
d[5].append('xsd')
d
我想要 output 作為; d={5:['acb','xsd'],6:'bhg',7:'cssd'}
你可以試試這個:
d = {5: 'acb', 6: 'bhg', 7: 'cssd'}
if type(d[5]) is list:
d[5].append('xsd')
else:
tmp = []
tmp.append(d[5])
tmp.append('xsd')
d[5] = tmp
你可以使用dict.pop
>>> d[5] = [d.pop(5), 'xsd']
從 Python 3.8
起,您可以使用walrus operator
使其更加靈活:
>>> d[5] = ( [*value, 'xsd']
if isinstance((value := d.pop(5)), list)
else [value, 'xsd']
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.