簡體   English   中英

創建詞典Python詞典

[英]Create Dictionary of Dictionary Python

我正在嘗試將字典(person_profile)的字典復制到新的字典字典(person_info)中,因為我試圖將兩個不同的字典(person_profile和person_attribute合並到person_info)中,而不必具有相同的長度和鍵值。 下面是我的代碼(我改變了變量只是為了讓它聽起來更簡單):

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} 
    })

但是上面的方法似乎創建了一個集合而不是字典。 我在其他文章中找不到如何做到這一點。 這個問題的推薦方法是什么?

==答案

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
    })

你實際上是取代person.nameperson.ageperson.occupationperson.gender每個人在列表中,而不是將它們合並的。

根據您的代碼,我將執行以下操作以將這兩個屬性放在字典中:

>>> 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})

我假設您要做的是以下內容。 您的代碼不像set那樣工作,但如果person_id匹配,只需將dict替換為其他dict

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM