比较Python字典并找到缺失的元素

问题描述 投票:0回答:2

我遇到了一个问题,我已经尝试了几天但没有得到任何结果。我想比较两本字典,一本字典中有“赛前”足球比赛,第二本字典中有“现场”足球比赛。

如果没有现场赛前比赛,我想将它们相互比较并打印出来。

示例1

pre = [{
        "Home": "Genoa",
        "Away": "Inter",
        "Match Full": "Genoa v Inter",
        "Start Data": "19 Lug",
        "Start Time": "21:30"
    },
    {
        "Home": "Parma",
        "Away": "Fiorentina",
        "Match Full": "Parma v Fiorentina",
        "Start Data": "17 Ago",
        "Start Time": "18:30"
    }]

live = [{
        "Home": "Dagon Star United FC",
        "Away": "Ispe FC",
        "Match Full": "Dagon Star United FC v Ispe FC"
    },
    {
        "Home": "Genoa",
        "Away": "Inter",
        "Match Full": "Genoa v Inter"
    }]

check = [[x for x in pre if x['Match Full'] != i['Match Full']] for i in live]

print(check)

我没有收到想要的结果,我也尝试了以下代码,但没有收到正确的结果。

示例2

pre = [{
        "Home": "Genoa",
        "Away": "Inter",
        "Match Full": "Genoa v Inter",
        "Start Data": "19 Lug",
        "Start Time": "21:30"
    },
    {
        "Home": "Parma",
        "Away": "Fiorentina",
        "Match Full": "Parma v Fiorentina",
        "Start Data": "17 Ago",
        "Start Time": "18:30"
    }]

live = [{
        "Home": "Dagon Star United FC",
        "Away": "Ispe FC",
        "Match Full": "Dagon Star United FC v Ispe FC"
    },
    {
        "Home": "Genoa",
        "Away": "Inter",
        "Match Full": "Genoa v Inter"
    }]

for x in pre:
    for i in live:
        if x['Match Full'] != i['Match Full']:
            print(x['Match Full'])

我想要得到的只是“实时”字典中缺少的赛前,在这种情况下,它应该只打印“帕尔马诉佛罗伦萨”,因为它在字典中丢失了

任何解决方案将不胜感激,提前谢谢您。

python dictionary comparison
2个回答
1
投票
#Create a list of value of 'Match Full' from live
live_lst = [x["Match Full"] for x in live] 

for x in pre:
    if x["Match Full"] not in live_lst:
        print(x["Match Full"])

#Output : Parma v Fiorentina

1
投票

这应该做

def get_set(matches):
    return set([match_['Match Full'] for match_ in matches])
    
pre_set= get_set(pre)
live_set = get_set(live)
print(pre_set-live_set) # {'Parma v Fiorentina'}
© www.soinside.com 2019 - 2024. All rights reserved.