Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
merging three dictionaries
#1
i have three dictionaries with distinct keys (no two have the same key). i need to merge all three into one dictionary and use the result in an expression, such as passing it as an argument in a function or method call, or doing a lookup on the combination. is this possible in one line?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
one = {"A": 0, "B": 0}
two = {"C": 1}
three = {"D": 3, "E": 0}
one.update(**two, **three)
print(one)
Skaperen likes this post
Reply
#3
And if you don't want to modify one of the existing dicts, you can just create a new one and populate it semi-directly.

one = {"A": 0, "B": 0}
two = {"C": 1}
three = {"D": 3, "E": 0}
new_dict = {**one, **two, **three}
print(new_dict)
With 3.9 you'll be able to use the pipe symbol operators do that as well.
Skaperen likes this post
Reply
#4
nice! i didn't know one could even do ** in {}.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Merging Dictionaries - Optimum Style? adt 5 2,886 Oct-09-2019, 05:26 PM
Last Post: adt
  merging dictionaries Skaperen 3 2,440 Nov-13-2018, 06:26 AM
Last Post: Skaperen
  merging two dictionaries Skaperen 17 10,516 Oct-05-2017, 12:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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