[英]Combining identical values against a list of dictionaries in Python
我正在使用python構建表。 該表的行包含在詞典列表中,如下所示:
table = [{ 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'No MFA', 'Action': 'Disable account and notify user' },
{ 'User' : 'janedoe', 'Profile' : 'Production', 'Risk' : 'Expired Password', 'Action': 'Reset password and notify user' },
{ 'User' : 'cookiedoe', 'Profile' : 'Non-Production', 'Risk' : 'Expired key', 'Action': 'Delete old key and notify user' },]
每當我檢測到不符合條件時,我都會運行一個函數來構建行。 我的目標是合並“用戶”和“個人資料”相同的行。 例如,如果Production中的johndoe也有過期的密碼,那么我希望他的字典看起來像這樣:
{ 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'No MFA, Expired password', Action: 'Disable account and notify user\n Reset password and notify user' }
當前的每一行都生活在稱為“行”的本地詞典中。 這就是我現在想要實現的方式:
for past_row in table:
past_user = past_row['User']
row_user = row['User']
past_profile = past_row['Profile']
row_profile = row['Profile']
if past_user == row_user and past_profile == row_profile:
past_row['Risk'] = "%s, %s" %(past_row['Risk'], row['Risk'])
past_row['Action'] = "%s\n %s" %(past_row['Action'], row['Action'])
我的Python腳本無休止地運行,沒有完成。 我感覺自己在低效率地檢查過去的行,而且我還很年輕,接受過Python語言教育。 圍着谷歌搜索只是讓我的邏輯更加混亂。 有人可以讓我挺直嗎?
好的,我想出了一個快速的解決方案。 它可以更高效地完成,但是,請記住您是Python的初學者,我將重點放在可讀性上。 它就到了(腳本可以按原樣執行):
# Import default-dictionary.
from collections import defaultdict
# Minimal sample, we want to merge johndoe.
table = [{ 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'No MFA', 'Action': 'Disable account and notify user' },
{ 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'Expired Password', 'Action': 'Reset password and notify user' },
{ 'User' : 'cookiedoe', 'Profile' : 'Non-Production', 'Risk' : 'Expired key', 'Action': 'Delete old key and notify user' },]
# Inline function definition for combinining risks/actions
# from multiple profiles.
combine_risks = lambda ps: ', '.join([p['Risk'] for p in ps])
combine_actions = lambda ps: ', '.join([p['Action'] for p in ps])
# Merge multiple profile dicts into one.
def combine_profiles(profiles):
return dict(
User=profiles[0]['User'],
Profile=profiles[0]['Profile'],
Risk=combine_risks(profiles),
Action=combine_actions(profiles)
)
# Profile - indices mapping.
prof2ind = defaultdict(set)
# Enumerate profiles and save information about which profiles
# have matching User and Profile.
for index, row in enumerate(table):
key = (row['User'], row['Profile'])
prof2ind[key].add(index)
new_table = []
# Finally, build merged table.
# 'indices' is a set holding indices of matching profile-sets.
for indices in prof2ind.values():
profiles = [table[i] for i in indices]
new_table.append(combine_profiles(profiles))
# Check the result.
print(new_table)
從某種意義上說,此腳本是通用的,可用於多個匹配的配置文件,而不僅僅是對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.