python - 在条件下追加到字典列表中的嵌套列表

标签 python list dictionary nested

我有 2 个共享信息的列表。首先,我想要一组唯一的名字(例如 list_person 有重复的 name 值);为此,我制作了一个新的词典列表。 然后,我想将 list_pets['pet'] 添加/附加到新字典中正确的 list_person['pets'] name 值,当 list_pets['person_id']list_person['id'] 匹配时。

为了澄清这里是我的代码 + 期望的输出:

我当前的代码:

list_person = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat']}, # you see that name values are repeated
              {'id': 678910, 'name': 'Bobby Bobs', 'pets': ['zebra']},
              {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse']},
              {'id': 141516, 'name': 'Lisa Bobs', 'pets': ['rabbit']}]

list_pets = [{'id': 'abcd', 'pet': 'shark', 'person_id': 12345}, #Bobby Bobs' pets
             {'id': 'efgh', 'pet': 'tiger', 'person_id': 678910}, #Bobby Bobs' pets
             {'id': 'ijkl', 'pet': 'elephant', 'person_id': 111213}, #Lisa Bobs' pets
             {'id': 'mnopq', 'pet': 'dog', 'person_id': 141516}] #Lisa Bobs' pets

output = []
for person, pet in zip(list_person, list_pets):
    t = [temp_dict['name'] for temp_dict in output]
    if person['name'] not in t:
        output.append(person)    # make a new list of dicts with unique name values
        for unique_person in output: # if they share ID, add the missing pets. 
            if person['id'] == pet['person_id']:
                unique_person['pets'].append(pet['pet'])
print(output)

期望的输出:

desired_out = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra', 'shark', 'tiger']},
                {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit', 'elephant', 'dog']}]

当前输出:

[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'shark', 'elephant']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'elephant']}]

我当前的输出没有显示所有正确的宠物。这是为什么;为了更接近解决方案,人们会给我什么建议?

最佳答案

这是一个非 Pandas 解决方案,它不依赖于 list_person 之间的顺序关系(又名“人”)和list_pets .所以我不假设 Bobby 的数据是两个列表中的前两个条目。

最初,output将是姓名到个人数据(包括宠物)的映射。和 ids将被维护以链接每个人的不同 ID - 通过有意使用对数据字典的引用而不是副本。

注意当一个人被添加到output ,它是作为一个深度复制完成的,因此它不会影响 list_person 中的原始项目。 .

import copy

output = {}  # dict, not list
ids = {}  # needed to match with pets which has person_id

for person in list_person:
    if (name := person['name']) in output:
        output[name]['pets'].extend(person['pets'])
        output[name]['id'].append(person['id'])
        ids[person['id']] = output[name]  # itentionally a reference, not a copy
    else:
        output[name] = copy.deepcopy(person)  # so that the pet list is created as a copy
        output[name]['id'] = [output[person['name']]['id']]  # turn id's into a list
        ids[person['id']] = output[name]  # itentionally a reference, not a copy

for pet in list_pets:
    # the values in ids dict can be references to the same object
    # so use that to our advantage by directly appending to 'pet' list
    ids[pet['person_id']]['pets'].append(pet['pet'])

output现在是:

{'Bobby Bobs': {'id': [12345, 678910],
                'name': 'Bobby Bobs',
                'pets': ['cat', 'zebra', 'shark', 'tiger']},
 'Lisa Bobs': {'id': [111213, 141516],
               'name': 'Lisa Bobs',
               'pets': ['horse', 'rabbit', 'elephant', 'dog']}
}

最后一步使其成为一个列表并且只使用一个 id对于每个人:

output = list(output.values())
for entry in output:
    entry['id'] = entry['id'][0]  # just the first id

最终 output :

[{'id': 12345,
  'name': 'Bobby Bobs',
  'pets': ['cat', 'zebra', 'shark', 'tiger']},
 {'id': 111213,
  'name': 'Lisa Bobs',
  'pets': ['horse', 'rabbit', 'elephant', 'dog']}]

如果您不介意多个 ID,请跳过上面的最后一步并将其保留在 output = list(output.values())。 .

关于python - 在条件下追加到字典列表中的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66973734/

相关文章:

python - 使用 kivy 更新多个标签

python - Stringtoknow ="value"我想在变量 stringtoknow 更改 python 中的值时运行函数

python - 如何在Anaconda Navigator中下载opencv-python库?

python - 检查元组列表是否是另一个元组的子集

python 3.x : Merge two dictionaries with same keys and values being array

python - 从行中提取名称

HTML/CSS : list button among themselves

python - 获取字典上存在特定键值对的列表

python - 如何将函数的单独字典输出合并到一个字典中?

dictionary - 名词、动词、形容词等的单独单词列表