Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create new dictionary
#1
If I have the following two dictionaries.

person1 = {
    "name" : "fred"
    "age" : 31
}

person2 = {
    "name" : "bob"
    "age" : 35
}
Can I easily create

person = {
   "name" : ("fred", "bob")
   "age" :(31, 35)
}
Reply
#2
Yes, to combine:
first you must add a comma at the end of each dictionary item
person1 = {
    "name" : "fred",
    "age" : 31
}
 
person2 = {
    "name" : "bob",
    "age" : 35
}

person = {}
person["name"] = (person1["name"], person2["name"])
person["age"] = (person1["age"], person2["age"])

print(person)
Output:
{'name': ('fred', 'bob'), 'age': (31, 35)}
Reply
#3
It is easier to group items if they are already in a collection.
people = [
    {"name" : "fred", "age" : 31},
    {"name" : "bob", "age" : 35},
    {"name" : "Mary", "age" : 33},
]

people_lists = {key:[d[key] for d in people] for key in people[0]}
print(people_lists)
Output:
{'name': ['fred', 'bob', 'Mary'], 'age': [31, 35, 33]}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create new dictionary angus1964 6 2,080 May-08-2022, 12:43 PM
Last Post: snippsat
  Create a dynamic Menu from a editable Dictionary. KiNeMs 1 2,305 Jan-28-2020, 04:27 AM
Last Post: Larz60+
  Need to create a dictionary from a *.csv 74razor 5 3,028 Dec-18-2019, 08:57 PM
Last Post: ichabod801
  Create a dictionary from a list klllmmm 3 2,965 Oct-06-2019, 05:50 PM
Last Post: Gribouillis
  Create XML from dictionary pygrrrl 7 104,694 Jul-29-2019, 08:33 PM
Last Post: pygrrrl
  Better way to create nested dictionary with defaultdict() x2mlh 8 21,687 Nov-30-2017, 08:10 PM
Last Post: buran
  create dictionary from **kwargs that include tuple bluefrog 2 4,889 Oct-26-2016, 10:24 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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