Concatenate two dictionaries - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Concatenate two dictionaries (/thread-21731.html) |
Concatenate two dictionaries - harish - Oct-11-2019 HI All, My requirement is little similar to concatenation of two dictionaries, Source data is: x = {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'} y = {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'} output should be ( {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'}, {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'} ) When I checked with online help, I found dictionaries update or merge or concatenation scenarios with below output, {'field1': 'test1', 'field2': 'test2', 'field3': 'test3','field4': 'test4', 'field5': 'test5', 'field6': 'test6'} Please suggest me the function or logic to concatenate two dictionaries. Thanks in Advance. Regards, Harish RE: Concatenate two dictionaries - buran - Oct-11-2019 x = {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'} y = {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'} z = (x, y) # this is tuple RE: Concatenate two dictionaries - harish - Oct-11-2019 Hi Buran, I tried with multiple options except this one. Thank you it's working. RE: Concatenate two dictionaries - strngr12 - Oct-12-2019 If you want to actually concatenate them you have to use the dict.update() method. tup = (x.update(y))This will create a single tuple(dict()): tup = ({'field1': 'test1', 'field2': 'test2', 'field3': 'test3','field4': 'test4', 'field5': 'test5', 'field6': 'test6'})as opposed to: tup = ({'field1': 'test1', 'field2': 'test2', 'field3': 'test3'}, y = {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'})which is just adding the two dictionaries to a tuple. |