Update python dictionary (add another value to existing key)

前端 未结 7 1495
青春惊慌失措
青春惊慌失措 2020-12-28 20:38

I have simple dictionary with key, value:

d = {\'word\': 1, \'word1\': 2}

I need to add another value (to make a list from values):

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 20:55

    Well you can simply use:

    d['word'] = [1,'something']
    

    Or in case the 1 needs to be fetched:

    d['word'] = [d['word'],'something']
    

    Finally say you want to update a sequence of keys with new values, like:

    to_add = {'word': 'something', 'word1': 'something1'}
    

    you could use:

    for key,val in to_add.items():
        if key in d:
            d[key] = [d[key],val]
    

提交回复
热议问题