seokhoonlee
seokhoonlee

Reputation: 1038

Create Dictionary of Dictionary Python

I am trying to copy a dictionary of dictionary (person_profile) into a new dictionary of dictionary (person_info) because I am trying to merge two different dictionaries (person_profile and person_attribute into person_info) with not necessarily same length and key value. Below are my code (I changed the variable just to make it sound more simple):

for person in person_profile:
    person_info.update({ 
        person.id :
       {'name' : person.name, 'age' : person.age} 
    })

# And call person_attribute again
for person in person_attribute:
    person_info.update({ 
        person.id :
       {'occupation' : person.occupation, 'gender' : person.gender} 
    })

However above method seems to create a set instead of dictionary. I couldn't find how to do so in other articles. What is a recommended approach to this problem?

== ANSWERED

for person in person_profile:
    person_info[person.id] = {'name' : person.name, 'age' : person.age}

for person in person_attribute:
    person_info[person.id].update({
        'occupation' : person.occupation, 'gender' : person.gender
    })

Upvotes: 3

Views: 593

Answers (2)

harukaeru
harukaeru

Reputation: 713

I assume what you want to do is the following. Your code is not working like set but simply replaces a dict with other dict if person_id matches.

class Person:
    def __init__(self, id, name, age, occupation, gender):
        self.id = id
        self.name = name
        self.age = age
        self.occupation = occupation
        self.gender = gender


person_info = dict()
person_profile = [Person(1, 'Jack', 17, '---', '---'), Person(2, 'Jane', 19, '---', '---')]
for person in person_profile:
    person_info.update({
        person.id :
       {'name' : person.name, 'age' : person.age}
    })

person_attribute = [Person(1, '---', '---', 'Senetor', 'Male'), Person(2, '---', '---', 'Nurse', 'Female')]
for person in person_attribute:
    data = person_info.get(person.id)
    attribute_dict = {'occupation' : person.occupation, 'gender' : person.gender}

    if data:
        data.update(attribute_dict)
    else:
        data = attribute_dict
print(person_info)

Upvotes: 1

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

You are actually replacing person.name and person.age with person.occupation and person.gender for each person in the list instead of merging them.

Based on your code, I would do the following in order to put both of those properties in a dictionary:

>>> import collections
>>> person_info = collections.defaultdict(dict)

>>> for person in person_profile:
...     person_info[person.id].update({'name': person.name, 'age': person.age}) 

>>> for person in person_attribute:
...     person_info[person.id].update({'occupation': person.occupation, 'gender': person.gender})

Upvotes: 1

Related Questions