Python Forum

Full Version: Create new dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
}
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)}
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]}