如何在python中比较具有不同键的两个字典的值

时间:2020-06-23 16:57:07

标签: python dictionary

我的足球比赛结果字典如下:

results = {
    "31 August 2019": [
        [
            {"Lazio": 2}, 
            {"Roma": 1}
        ]
    ], 
    "1 September 2019": [
        [
            {"AC Milan": 0}, 
            {"Napoli": 3}
        ],
        [
            {"Udinese": 1}, 
            {"Fiorentina": 1}
        ]
    ]
}

[{“” Lazio“:2},{” Roma“:1}]表示Lazio VS Roma,得分:2-1

我需要的是通过比较一场比赛的两本词典来获得每场比赛的冠军。我已经尝试过了:

for date, matches in results.items():
    for match in matches:
        if match[0].value() > match[1].value(): #I'm Stuck on this
            print(date)
            print("the winner is :", match[0].key())
        elif match[0].value() < match[1].value(): #I'm Stuck on this
            print(date)
            print("the winner is :", match[1].key())
        else:
            print(date)
            print("the match between ",match[0].key()," VS ",match[1].key()," was even")

当然该代码不起作用,但我希望您能理解我的意思。 如果您有更好的格式来保存结果,请告诉我。 非常感谢

3 个答案:

答案 0 :(得分:1)

与仅使用2元组{'AC Milan': 0}之类的字典相比,您的字典('AC Milan', 0)并不是一种方便的格式。

以下是关于如何提取数据的一种建议:

results = {'1 September 2019': [[{'AC Milan': 0}, {'Napoli': 3}],
                                [{'Udinese': 1}, {'Fiorentina': 1}]],
           '31 August 2019': [[{'Lazio': 2}, {'Roma': 1}]]}

for date, matches in results.items():

    for match in matches:
        t1, t2 = [next(iter(d.items())) for d in match]
        team1, score1 = t1
        team2, score2 = t2

        if score1 > score2:
            print(team1)
        elif score2 > score1:
            print(team2)
        else:
            print("the match between {} VS {} was even"
                  .format(team1, team2))

礼物:

Napoli
the match between Udinese VS Fiorentina was even
Lazio

将它们更改为2元组,这变得容易得多。例如:

results = {'1 September 2019': [[('AC Milan', 0), ('Napoli', 3)],
                                [('Udinese', 1), ('Fiorentina', 1)]],
           '31 August 2019': [[('Lazio', 2), ('Roma', 1)]]}

for date, matches in results.items():

    for match in matches:
        t1, t2 = match
        team1, score1 = t1
        team2, score2 = t2

        # ... etc ...

(或者甚至可以用for t1, t2 in matches:代替for match ...及其后的语句。)

答案 1 :(得分:0)

代码中的主要问题是字典没有.value()方法,即使它们只有一个键,值对。对于提供的数据结构,您需要执行类似的操作,通过list(dict.values())[0]从每个单个元素字典中获取值(请注意,这是next(iter(d.items()))的替代方法(并且是较慢的方法)在其他答案中看到):

for date,matches in results.items():
    for match in matches:
        if list(match[0].values())[0] > list(match[1].values())[0]:
            print(date)
            print("the winner is :", list(match[0].keys())[0])
        elif list(match[0].values())[0] < list(match[1].values())[0]:
            print(date)
            print("the winner is :", list(match[1].keys())[0])
        else:
            print(date)
            print("the match between ",list(match[0].keys())[0],
            " VS ",list(match[1].keys())[0]," was even")

但是我也同意其他张贴者的看法,认为可以改进数据结构以减轻这种状况。

我的转换建议是在每个日期列出2个元素的词典(静止键=团队,价值=得分)。然后,您可以执行类似的操作,感觉简单得多:

results = {"31 August 2019": [{"Lazio": 2, "Roma": 1}], "1 September 2019" : [{"AC Milan":0,"Napoli":3},{"Udinese":1,"Fiorentina":1}]}

for date,matches in results.items():
    for match in matches:
        print(date)
        maxi = max(match, key=match.get)
        mini = min(match, key=match.get)
        if match[maxi] == match[mini]:
            print("the match between ",maxi," VS ",mini," was even") 
        else:
            print('the winner is: ', maxi)

答案 2 :(得分:0)

match[0]match[1]都是字典,没有值方法。字典可以包含多个键和值,因此拥有“值”方法来检索一个值毫无意义。

相反,它具有.values()方法,该方法返回可用于迭代所有值的迭代器。如果您确定字典总是只包含一个值,则可以使用next(iter(match[0].values()))来检索它。如果有多个值,它将仅检索一个值;如果dict为空,则将引发异常。因此,您的比较看起来像if next(iter(match[0].values())) > next(iter(match[1].values())):

但是,如果您可以控制results的结构,则可以避免这种情况。使用字典来存储一个键值对是不合适的。请改用元组。