搜索更优雅(更少代码)的方式来比较多个字典 [英] Searching for a more elegant (less code) way to compare multiple dicts

查看:103
本文介绍了搜索更优雅(更少代码)的方式来比较多个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前段时间,我问了一个问题,关于相互比较两个字典,以便检测相同的密钥并保持最高重复值。
这个社区带有一个解决方案,使我可以相互比较2个字典,并将其最高价值存储在一个新字典中,如果需要,我可以将其与另一个字典进行比较。

a while ago i asked a question about comparing 2 dicts to eachother, in order to detect same key's and keep the highest value of duplicates. this community came with the a soltion which allowed me to compare 2 dicts to eachother and store the highest value of it in a new dict, which i can then compare to another dict if neccesary.

,但是随着字典数量的增加,代码本身也越来越大。

but as the number of dicts are getting higher, the code itself keeps getting larger.

for key in dict1:
    if key not in dict2 or dict1[key] > dict2[key]:
        dict2[key] = dict1[key]
dict2a = {**dict1, **dict2}

for key in dict2a:
    if key not in dict3 or dict2a[key] > dict3[key]:
         dict3[key] = dict2a[key]
dict3a = {**dict2a, **dict3}

for key in dict3a:
    if key not in dict4 or dict3a[key] > dict4[key]:
        dict4[key] = dict3a[key]
dict4a = {**dict3a, **dict4}

我正试图提出一个解决所有这些问题的解决方案。
这个问题也和另一个问题挂在一起,但是为了使解决方案分开,我在另一个帮助问题中问这个问题(如何打开多个json txt文件而不会出错并停止)。
尝试获得更短的打开多个txt文件

Im trying to come up with a solution that will iterate over all these dicts. This question also hangs together with another question, but to keep solutions seperated, i ask this question in another help-question (how to open up multiple json txt files without getting errors and stops). Trying to get shorter way of opening multiple txt files

简而言之,atm im会为每个已参加的比赛创建一个字典,以玩家名作为键,其分数为一个值。
需要通过此dict比较来过滤参加过1场以上比赛的玩家姓名,并仅保留其最高得分。
但是,对此的另一种解决方案是将所有这些不同的字典存储在一个大嵌套字典中。那至少是我老师给我的暗示。但是我找不到一种将嵌套的字典相互比较的方法,因此atm会绑定所有这些单独的字典。

In short, atm im creating a dict for each played contest, with playernames as key's and their scores a values. This dict comparison is needed to filter playernames who attended to more then 1 contest, and to keep only their highest score. But perhaps another solution to this is to store all those different dicts in 1 big nested dict. That is at least the hint my teacher gave me. But i cannot find a way to compare nested dicts to eachother, and thus atm im bound to all these seperated dicts.

如果不清楚任何信息,请让我知道,所以我可以尝试进一步清除它。

If any info is unclear please let me know so i can try to clearify it more.

thnx

更新:
的示例在比较后达到:

update: an example of what is reached after a comparison:

dict1 = {"name1": 100, "name2": 20, "name4": 111}
dict2 = {"name4": 112, "name5": 23}

compared_dict = {"name1": 100, "name2": 20, "name4": 112, "name5": 23}


推荐答案

所以这两个规则是:


  1. 过滤出重复项

  2. 如果最新词典的得分大于旧词典的得分,则包括一个

您正在复制很多代码...编码最佳实践的第一条规则是DRY(请勿重复)

You are copying a lot of code... one of the first rules of coding best practices is DRY (don't repeat yourself!)

让我们定义一个合并新旧字典的方法

Let's define a method to merge our old and new dictionaries

def merge_dictionaries(old, new):
    changes = {}
    # keep the old one, don't edit the new one
    copy = old.copy()
    for player in new.keys():
        new_score = new[player]
        try:
            old_score = old[player]
        except KeyError:
            # if player doesn't exist in the old set, add them to the changes
            changes[player] = new_score
            continue
        if new_score > old_score:
            changes[player] = new_score
    copy.update(changes)
    return copy

下一步是使用上述方法遍历包含词典名称和分数的词典列表,以得出最终结果。

The next step would be to iterate over a list of these dictionaries containing playernames and scores to total to a final result using the method above.

一个解决方案可能看起来像这样:

One solution may look like this:

def final_result(list_of_games):
    final = {}
    for results in list_of_games:
        final = merge_dictionaries(final, results)
    return final

工作示例:

def merge_dictionaries(old, new):
    changes = {}
    # keep the old one, don't edit the new one
    copy = old.copy()
    for player in new.keys():
        new_score = new[player]
        try:
            old_score = old[player]
        except KeyError:
            # if player doesn't exist in the old set, add them to the changes
            changes[player] = new_score
            continue
        if new_score > old_score:
            changes[player] = new_score
    copy.update(changes)
    return copy

def final_result(list_of_games):
    final = {}
    for results in list_of_games:
        final = merge_dictionaries(final, results)
    return final

games = [
    {'kevin': 1, 'jack': 5},
    {'kevin': 2, 'blueberry': 1, 'jack': 3},
    {'kevin': 1, 'blueberry': 5, 'jack': 10}
    ]

print(final_result(games))

哪个输出

{'kevin': 2, 'jack': 10, 'blueberry': 5}

这篇关于搜索更优雅(更少代码)的方式来比较多个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆