通过Python中的类似值合并两个嵌套字典列表

问题描述 投票:1回答:1

我有两个嵌套字典列表:

lofd1 = [{'A': {'facebook':{'handle':'https://www.facebook.com/pages/New-Jersey/108325505857259','logo_id': None}, 'contact':{'emails':['[email protected]','[email protected]']},'state': 'nj', 'population':'12345', 'capital':'Jersey','description':'garden state'}}]
lofd2 = [{'B':{'building_type':'ranch', 'city':'elizabeth', 'state':'nj', 'description':'the state close to NY'}}]

我需要:

  • 使用“state”键的值合并列表中的类似词典(例如,将“state”=“nj”的所有词典合并到一个词典中
  • 它应该包括两个字典中存在的键/值组合(例如,两者的“状态”应为“nj”)
  • 它应该包括键/值组合,这些组合不存在于其中一个词典中(例如,来自lofd1的“人口”,“资本”和来自lofd2的“building_type”,“city”)。
  • 应排除字典中的某些值,例如“logo_id”:无
  • 将两个字典中的“description”中的值放入字符串列表中,例如“”description“:['garden state','state near NY']'

最终数据集应如下所示:

lofd_final = [{'state': 'nj', 'facebook':{'handle':'https://www.facebook.com/pages/New-Jersey/108325505857259'},'population':'12345', 'capital':'Jersey', 'contact':{'emails':['[email protected]','[email protected]']}, 'description': ['garden state','the state close to NY'],'building_type':'ranch', 'city':'elizabeth'}]

什么是有效的解决方案?

python-3.x list dictionary intersection
1个回答
0
投票

这是一个非常具体的解决方案。就时间复杂性而言; O(n*m)n是列表中的dicionaries数量,m是字典中键的数量。您只需查看一次每个字典中的每个键。

def extract_data(lofd, output):
    for d in lofd:
        for top_level_key in d: # This will be the A or B key from your example
            data = d[top_level_key] 
            state = data['state']
            if state not in output: # Create the state entry for the first time
                output[state] = {}
            # Now update the state entry with the data you care about
            for key in data:
                # Handle descriptions
                if key == 'description':
                    if 'description' not in output[state]:
                        output[state]['description'] = [data['description']]
                    else:
                        output[state]['description'].append(data['description'])
                # Handle all other keys
                else:
                    # Handle facebook key (exclude logo_id)
                    if key == 'facebook':
                        del data['facebook']['logo_id']
                    output[state][key] = data[key]

output = {}
extract_data(lofd1, output)
extract_data(lofd2, output)
print(list(output.values()))

output将是一个dicts的词典,顶级键作为状态。要将其转换为您指定的方式,只需将值提取到一个平面列表中:list(output.values())(参见上面的示例)。

注意:我假设不需要深层复制。所以在你提取数据后,我假设你不去操纵lofd1lofd2中的值。这也完全基于给出的规格,例如如果需要排除更多嵌套键,则需要自己添加额外的过滤器。

© www.soinside.com 2019 - 2024. All rights reserved.