Python Forum
Concatenate two dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Concatenate two dictionaries
#1
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
Reply
#2
x = {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'}
y = {'field4': 'test4', 'field5': 'test5', 'field6': 'test6'}
z = (x, y) # this is tuple
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hi Buran,
I tried with multiple options except this one.
Thank you it's working.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Concatenate str JohnnyCoffee 2 2,879 May-01-2021, 03:58 PM
Last Post: JohnnyCoffee
  Concatenate two dataframes moralear27 2 1,833 Sep-15-2020, 08:04 AM
Last Post: moralear27
  can only concatenate str (not "int") to str gr3yali3n 6 4,020 May-28-2020, 07:20 AM
Last Post: pyzyx3qwerty

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020