Copying a key/value from one dictionary into another

前端 未结 2 982
慢半拍i
慢半拍i 2021-01-12 08:29

I have a dict with main data (roughly) as such: {\'UID\': \'A12B4\', \'name\': \'John\', \'email\': \'hi@example.com}

and I have another dict like:

相关标签:
2条回答
  • 2021-01-12 09:15

    you want to use the dict.update method:

    d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
    d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
    d1.update(d2)
    

    Outputs:

    {'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}
    

    From the Docs:

    Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

    0 讨论(0)
  • 2021-01-12 09:17

    If you want to join dictionaries, there's a great built-in function you can call, called update.

    Specifically:

    test = {'A': 1}
    test.update({'B': 2})
    test
    >>> {'A':1, 'B':2}
    
    0 讨论(0)
提交回复
热议问题