私信  •  关注

Pradip

Pradip 最近创建的主题
Pradip 最近回复了
4 年前
回复了 Pradip 创建的主题 » 比较python中字典列表中的值

此代码将在线性时间内解决您的问题,即O(n),其中n是字典长度的增长顺序。只考虑那些 Id 两者兼而有之 title location 并将忽略其余部分。

from collections import Counter

data = [{"Id": 1, "title":"example1"},
        {"Id": 2, "title":"example2"},
        {"Id": 3, "title":"example3"},
        {"Id": 4, "title":"example4"},
        {"Id": 1, "location":"city1"},
        {"Id": 2, "location":"city2"},
        {"Id": 4, "location":"city4"},
        {"Id": 5, "location":"city5"}]

paired_ids = set([key for key, val in dict(Counter([item["Id"] for item in data])).items() if val == 2]) # O(n)

def combine_dict(data):
    result = {key: [] for key in paired_ids} # O(m), m: number of paired ids (m <= n/2)
    for item in data: # O(n)
        items = list(item.items())
        id, tl, val = items[0][1], items[1][0], items[1][1]

        if id in paired_ids: # O(1), as paired_ids is a set lookup takes O(1)
            result[id].append({tl: val})

    return [{"Id": id, "title": lst[0]["title"], "location": lst[1]["location"]} for id, lst in result.items()] # O(n)


print(*combine_dict(data), sep="\n")

输出:

{'Id': 1, 'title': 'example1', 'location': 'city1'}
{'Id': 2, 'title': 'example2', 'location': 'city2'}
{'Id': 4, 'title': 'example4', 'location': 'city4'}