根据条件将多个词典的列表组合成单个词典

Combine a list of multiple dictionaries into on single dict based on condition

我想合并一些字典,条件是只要它们在 ageexperience 中具有相同的值,那么我需要合并所有 dict 并保留字典不低于这个条件。

我有以下词典列表:

lst = [
        {
            "Game": "Lego",
            "players": [         
            {   "training":"2",
                "Age": "28",
                "Experience": "no",
                "Score": [
                    {
                        "Alicia": 87
                    }
                ]
            },
                {
                    "Age": "20",
                    "Experience": "yes",
                    "Score": [
                        {
                            "Alex": 230
                        }
                    ]
                },
                {
                    "Age": "20",
                    "Experience": "yes",
                    "Score": [
                        {
                            "juana": 275
                        }
                    ]
                }
            ],
            "season": "summer"

        }
    ]

输出应如下所示:

[
        {
            "Game": "Lego",
            "players": [
            {   "training":"2",
                "Age": "28",
                "Experience": "no",
                "Score": [
                    {
                        "Alicia": 87
                    }
                ]
            },         
                {
                    "Age": "20",
                    "Experience": "yes",
                    "Score": [
                        {
                            "Alex": 230
                        },
                        {
                            "juana": 275
                        }
                    ]
                }
            ],
            "season": "summer"
        }
    ]

我在这一步后无法检查 age/experience 是否相等。

for d in lst:
        for i, sd in enumerate(d['players']):
            d['players'][i] = {k: v for k, v in d['players'][i].items()}

注:

请注意,此代码非常混乱,可以做得更好,但我认为它可以完成工作:

    result_lst = []

for game_dict in lst:

    result_dict = {}
    result_dict['Game'] = game_dict['Game']
    result_dict['players'] = []
    result_dict['season'] = game_dict['season']

    for player_dict1 in game_dict['players']:

        starting_idx = game_dict['players'].index(player_dict1) + 1

        for player_dict2 in game_dict['players'][starting_idx:]:

            if player_dict1['Age'] == player_dict2['Age'] and player_dict1['Experience'] == player_dict2['Experience']:

                age = player_dict1['Age']
                experience = player_dict1['Experience']

                for result_player in result_dict['players']:

                    if age == result_player['Age']:

                        if player_dict1['Score'][0] not in result_player['Score']:
                            result_player['Score'].append(player_dict1['Score'][0])

                        if player_dict2['Score'][0] not in result_player['Score']:
                            result_player['Score'].append(player_dict2['Score'][0])

                        break
                
                else:

                    players_dict = {'Age': age,
                                    'Experience': experience,
                                    'Score': [player_dict1['Score'][0],
                                            player_dict2['Score'][0],
                                    ]
                    }

                    result_dict['players'].append(players_dict)
    
    in_result_dict = True

    for player_dict in game_dict['players']:
        
        for result_players in result_dict['players']:
            for result_player in result_players['Score']:
                
                if player_dict['Score'][0] == result_player:
                    in_result_dict = False
                    break

        if in_result_dict:
            result_dict['players'].append(player_dict)

    result_lst.append(result_dict)


print(result_lst)

另请注意,这种存储信息的方式过于冗余,难以访问数据并对其进行迭代,请考虑对其进行重构。

无论如何,输出是:

[{'Game': 'Lego', 
'players': [{'Age': '20', 
            'Experience': 'yes', 
            'Score': [{'Alex': 230}, {'juana': 275}]}, 
            
            {'Age': '28', 
                'Experience': 'yes', 
                'Score': [{'Alicia': 987}]}], 
'season': 'summer'}]

你可以试试这个。这里我尝试

1 将玩家列表转换为数据框 2 然后在 df 上进行分组以匹配 Age 和 experience 并获得 Score。 3 将这个dataframe转回dict,之后更新为原来的lst

import pandas as pd
lst = [] #Replace this with your list.
players = lst[0]['players']
print('Players before update\n', players)

df = pd.DataFrame.from_dict(players)
df_new = df.groupby(['Age','Experience'])['Score'].sum().reset_index()
players = df_new.to_dict('records')    
print('Players after update \n', players)    

print('lst before update\n', lst)
lst[0]['players'] = players
print('lst after update \n', lst)

输出:

Players before update
 [{'Age': '20', 'Experience': 'yes', 'Score': [{'Alex': 230}]}, {'Age': '20', 'Experience': 'yes', 'Score': [{'juana': 275}]}]
Players after update 
 [{'Age': '20', 'Experience': 'yes', 'Score': [{'Alex': 230}, {'juana': 275}]}]
lst before update
 [{'Game': 'Lego', 'players': [{'Age': '20', 'Experience': 'yes', 'Score': [{'Alex': 230}]}, {'Age': '20', 'Experience': 'yes', 'Score': [{'juana': 275}]}], 'season': 'summer'}]
lst after update 
 [{'Game': 'Lego', 'players': [{'Age': '20', 'Experience': 'yes', 'Score': [{'Alex': 230}, {'juana': 275}]}], 'season': 'summer'}]