Python Forum

Full Version: Concatenate two dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
x = {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'}
y = {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'}
z = (x, y) # this is tuple
Hi Buran,
I tried with multiple options except this one.
Thank you it's working.
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.