Update python dictionary (add another value to existing key)

前端 未结 7 1499
青春惊慌失措
青春惊慌失措 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条回答
  •  梦毁少年i
    2020-12-28 21:07

    You can create your dictionary assigning a list to each key

    d = {'word': [1], 'word1': [2]}
    

    and then use the following synthases to add any value to an existing key or to add a new pair of key-value:

    d.setdefault(@key,[]).append(@newvalue)
    

    For your example will be something like this:

    d = {'word': [1], 'word1': [2]}
    d.setdefault('word',[]).append('something')
    d.setdefault('word1',[]).append('something1')
    d.setdefault('word2',[]).append('something2')   
    print(d)
    {'word': [1, 'something'], 'word1': [2, 'something1'], 'word2': ['something2']}
    

提交回复
热议问题