首页 > 解决方案 > 从嵌套字典中提取公共值以及主键

问题描述

我们正在开展一个项目,我们需要在其中找到父母之间共同的孩子。数据集是一个寄存器 og 人名、数字和孩子的人号(大约 600 人) 我们想为孩子找到父母,这意味着我们需要在“孩子”下找到两个人共享相同人号的实例'。

我们已将所有人放入一个字典中,并将孩子(因为不止一个)放入每个人的单独字典中。我们已经成功地将所有孩子的 Person-number 从字典中取出,但现在是什么。我们需要知道他们连接到哪些“父母”并找到他们的父母对!帮助。字典看起来像这样:

Ages = []
Gender = []   
DadAges = []  
MomAges = []
findchildren = False  
findchildren1 = False
register = dict()
index = 0

for line in infile:
    #Add all information to a dict called register:
    # The dict, register, contains a dict for each person named [1-500]
    details = line.strip()
    if line.startswith("CPR"):
        register[index] = {"CPR": details[5:]}
    if line.startswith("First name"):
        register[index].update({"First name": details[12:]})
    if line.startswith("Last name"):
        register[index].update({"Last name": details[11:]})
    if line.startswith("Height"):
        register[index].update({"Height": details[8:]})
    if line.startswith("Weight"):
        register[index].update({"Weight": details[8:]})
    if line.startswith("Eye color"):
        register[index].update({"Eye color":details[11:]})
    if line.startswith("Blood type"):
        register[index].update({"Blood type": details[12:]})
    if line.startswith("Children"):
        register[index].update({"Children": details[10:].split()})
    if line == "\n":
        index += 1

输出也看起来像这样,其中每个数字都是人

3 {'CPR': '230226-9781', 'First name': 'Anton', 'Last name': 'Gade', 'Height': '201', 'Weight': '65', 'Eye color': 'Black', 'Blood type': 'A+', 'Children': ['081154-2786', '120853-1151', '050354-4664']}
4 {'CPR': '120194-9148', 'First name': 'Belina', 'Last name': 'Pedersen', 'Height': '160', 'Weight': '87', 'Eye color': 'Black', 'Blood type': 'O-'}
5 {'CPR': '220567-1489', 'First name': 'Mikael', 'Last name': 'Wad', 'Height': '175', 'Weight': '86', 'Eye color': 'Green', 'Blood type': 'A-', 'Children': ['260195-4304', '081295-4166']}
6 {'CPR': '141087-7452', 'First name': 'Inger', 'Last name': 'Nielsen', 'Height': '184', 'Weight': '101', 'Eye color': 'Grey', 'Blood type': 'AB-'}

做这个的最好方式是什么?我们很空白☺️

标签: pythondatabasefiledictionaryextract

解决方案


这是一个函数,它将返回任何两个人员字典之间的共同子项。

def find_common_children(parent_a, parent_b):
    return set(parent_a["Children"]).intersection(set(parent_b["Children"])

如果你想从孩子那里找到一对父母,那就另当别论了。你会想要构建另一个数据结构,可能是这样的

{
    child_id: [parent_a_id, parent_b_id],
    # etc. 
}

然后在这个字典中通过子 ID 进行简单的查找。你可以像这样构造这个字典:

from collections import defaultdict
# defaultdict just simplifies working with dicts whose values are collections
# in our case, we'll use lists for the values

parents_by_child = defaultdict(list)
for parent, data in registry.items():
    for child in data["Children"]: 
# make sure you create your registry with Children: [] if there are no children
# otherwise this line ^ will produce errors
    parents_by_child[child].append(parent["CPR"])

我还应该指出,创建一个每个键都是其索引的 dict 可能不是您想要做的。在这种情况下,您可以使用一个列表,它会自动从 0 索引到 len -1。当您需要通过键查找某些内容时,请使用 dicts。


推荐阅读