繁体   English   中英

将值添加到 Python 中的字典中的特定键

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM