将嵌套字典的键替换为另一个字典的值(两个字典的键相等))

时间:2015-12-07 10:00:41

标签: python dictionary

我有两个字典,dict1dict2,我想用键值对构造新的字典(或操纵dict1)(dict2:value的值dict1 dict2 [其中dict的密钥和dict1 = {'key18': {'key7': 'mon', 'key4': 'tues', 'key25': {'key5': {'key9': {'key24': 'wed', 'key13': 'yo', 'key17': 'go', 'key2': {'key24': 'to', 'key17': 'so', 'key2': 'mo', 'key12': 'kato'}}, 'key17': 'talo'}, 'key10': {'key9': {'key24': 'ryan', 'key15': 'swan toro', 'key13': 'masan.com'}, 'key23': 'qua-la-sa'}, 'key19': 'pirat9333', 'key16': {'key11': 'stepg-sdd:sdf', 'key20': 'asfd.asf'}, 'key21': {'key6': 'Tran swa', 'key3': {'key13': '1123', 'key8': 'ryan', 'key1': 'http://swan.com'}}, 'key22': {'key9': {'key24': 'mnhfg', 'key17': 'ejs-33', 'key2': {'key24': 'qwqwa-wnnf', 'key2': '213bvn'}}, 'key17': '1234bfh'}}}} dict2 = {'key1': 'aa', 'key2': 'ab', 'key3': 'ac', 'key4': 'ad', 'key5': 'ae', 'key6': 'af', 'key7': 'ag', 'key8': 'ah', 'key9': 'ai', 'key10': 'aj', 'key11': 'ak', 'key12': 'al', 'key13': 'am', 'key14': 'an', 'key15': 'ao', 'key16': 'ap', 'key17': 'aq', 'key18': 'ar', 'key2': 'as', 'key19': 'at', 'key20': 'au', 'key21': 'av', 'key22': 'aw', 'key23': 'ax', 'key24': 'ay', 'key25': 'az'} dict3 = {} dict3 = {v:dict1.get(k) for k,v in dict2.iteritems()} print dict3 的密钥相同])

dict1 = {'ar': {'ag': 'mon', 'ad': 'tues', 'az': {'ae': {'ai': {'ay': 'wed', 'am': 'yo', 'aq': 'go', 'ab': {'ay': 'to', 'aq': 'so', 'ab': 'mo', 'al': 'kato'}}, 'aq': 'talo'}, 'aj': {'key9': {'key24': 'ay', 'ao': 'swan toro', 'am': 'masan.com'}, 'ax': 'qua-la-sa'}, 'at': 'pirat9333', 'ap': {'ak': 'stepg-sdd:sdf', 'au': 'asfd.asf'}, 'av': {'af': 'Tran swa', 'ac': {'am': '1123', 'ah': 'ryan', 'aa': 'http://swan.com'}}, 'aw': {'ai': {'ay': 'mnhfg', 'aq': 'ejs-33', 'ab': {'ay': 'qwqwa-wnnf', 'ab': '213bvn'}}, 'aq': '1234bfh'}}}}

预期输出为:

output = {'aa': None, 'ac': None, 'ae': None, 'ad': None, 'ag': None, 'af': None, 'ai': None, 'ah': None, 'ak': None, 'aj': None, 'am': None, 'al': None, 'ao': None, 'an': None, 'aq': None, 'ap': None, 'as': None, 'ar': {'key25': {'key5': {'key17': 'talo', 'key9': {'key17': 'go', 'key2': {'key17': 'so', 'key2': 'mo', 'key12': 'kato', 'key24': 'to'}, 'key13': 'yo', 'key24': 'wed'}}, 'key22': {'key17': '1234bfh', 'key9': {'key17': 'ejs-33', 'key2': {'key2': '213bvn', 'key24': 'qwqwa-wnnf'}, 'key24': 'mnhfg'}}, 'key21': {'key3': {'key1': 'http://swan.com', 'key8': 'ryan', 'key13': '1123'}, 'key6': 'Tran swa'}, 'key19': 'pirat9333', 'key16': {'key20': 'asfd.asf', 'key11': 'stepg-sdd:sdf'}, 'key10': {'key23': 'qua-la-sa', 'key9': {'key15': 'swan toro', 'key13': 'masan.com', 'key24': 'ryan'}}}, 'key7': 'mon', 'key4': 'tues'}, 'au': None, 'at': None, 'aw': None, 'av': None, 'ay': None, 'ax': None, 'az': None}

我得到的输出是,

dict1 = {"key1":{"key3":"value1","key2":"value2","key4":{"key5":"value3","key6":{"key7":"value4","key8":{"key9":"value5","key10":"value6","key55":"value7"}},"key11":{"key12":"value8","key13":"value9"},"key14":[{"key15":"value10","key16":"value11","key17":"value12"},{"key15":"value13","key16":"value14","key17":"value15"}]}}}

dict2 = {"key1":"ab","key2":"bc","key3":"cd","key4":"de","key5":"ef","key6":"fg","key7":"gh","key8":"hi","key9":"ij","key10":"jk","key55":"kl","key11":"lm","key12":"mn","key13":"no","key14":"op","key15":"pq","key16":"qr","key17":"qs"}

列表为值的新示例

List<AssessmentWithRemidiationViewModel> activeAssessmentWithRemidiation = AssessmentRemidiationRelay.GetActiveAssessmentWithRemediation(null);
var query_b = (from b in activeAssessmentWithRemidiation
               where ((b.AssessorID == ContextSession.StaffID) 
                        || (b.ModuleLead == ContextSession.StaffID) 
                        || (b.SeniorStaffID == ContextSession.StaffID)) 
                        && b.ClinicalSupervisorCheck == true
                    select b).ToList();

1 个答案:

答案 0 :(得分:2)

如果你的第一个dict是嵌套的,而第二个dict是平的,你需要走第一个dict,而不是使用递归函数而不是普通循环。像这样:

def walk(dict1, dict2):
    output = {}
    for key, value in dict1.iteritems():
        if key not in dict2: raise Exception('key {0!r} found in dict1 but not dict2'.format(key))
        if dict2[key] in output: raise Exception('duplicate value {0!r} found in dict2'.format(dict2[key]))
        if isinstance(value, dict):
            output[dict2[key]] = walk(value, dict2)
        else:
            output[dict2[key]] = value
    return output

dict1 = {'key18': {'key7': 'mon', 'key4': 'tues', 'key25': {'key5': {'key9': {'key24': 'wed', 'key13': 'yo', 'key17': 'go', 'key2': {'key24': 'to', 'key17': 'so', 'key2': 'mo', 'key12': 'kato'}}, 'key17': 'talo'}, 'key10': {'key9': {'key24': 'ryan', 'key15': 'swan toro', 'key13': 'masan.com'}, 'key23': 'qua-la-sa'}, 'key19': 'pirat9333', 'key16': {'key11': 'stepg-sdd:sdf', 'key20': 'asfd.asf'}, 'key21': {'key6': 'Tran swa', 'key3': {'key13': '1123', 'key8': 'ryan', 'key1': 'http://swan.com'}}, 'key22': {'key9': {'key24': 'mnhfg', 'key17': 'ejs-33', 'key2': {'key24': 'qwqwa-wnnf', 'key2': '213bvn'}}, 'key17': '1234bfh'}}}}
dict2 = {'key1': 'aa', 'key2': 'ab', 'key3': 'ac', 'key4': 'ad', 'key5': 'ae', 'key6': 'af', 'key7': 'ag', 'key8': 'ah', 'key9': 'ai', 'key10': 'aj', 'key11': 'ak', 'key12': 'al', 'key13': 'am', 'key14': 'an', 'key15': 'ao', 'key16': 'ap', 'key17': 'aq', 'key18': 'ar', 'key2': 'as', 'key19': 'at', 'key20': 'au', 'key21': 'av', 'key22': 'aw', 'key23': 'ax', 'key24': 'ay', 'key25': 'az'}
output = walk(dict1, dict2)
print output

结果输出:

{'ar': {'az': {'ae': {'aq': 'talo', 'ai': {'aq': 'go', 'ay': 'wed', 'as': {'aq': 'so', 'ay': 'to', 'as': 'mo', 'al': 'kato'}, 'am': 'yo'}}, 'aj': {'ai': {'ay': 'ryan', 'am': 'masan.com', 'ao': 'swan toro'}, 'ax': 'qua-la-sa'}, 'ap': {'ak': 'stepg-sdd:sdf', 'au': 'asfd.asf'}, 'at': 'pirat9333', 'aw': {'aq': '1234bfh', 'ai': {'aq': 'ejs-33', 'ay': 'mnhfg', 'as': {'ay': 'qwqwa-wnnf', 'as': '213bvn'}}}, 'av': {'ac': {'aa': 'http://swan.com', 'ah': 'ryan', 'am': '1123'}, 'af': 'Tran swa'}}, 'ad': 'tues', 'ag': 'mon'}}

我添加了一些您可能想要处理的异常。当dict2不包含您在dict1中找到的密钥时,第一个异常会处理这种情况。第二个处理dict2中两个相同值的情况,这会导致它们写入output中的相同键,从而丢失一些数据。

此外,我不确定您是否知道,但您的dict2声明包含两个'key2'个实例。即使这不是问题(也可能是),你应该处理它。

P上。 S.如果你想走路列表,你需要两个走路方法:一个用于dicts,另一个用于列表,因为它们具有明显不同的逻辑。

def walk(dict1, dict2):
    output = {}
    for key, value in dict1.iteritems():
        if key not in dict2: raise Exception('key {0!r} found in dict1 but not dict2'.format(key))
        if dict2[key] in output: raise Exception('duplicate value {0!r} found in dict2'.format(dict2[key]))
        if isinstance(value, dict):
            output[dict2[key]] = walk(value, dict2)
        elif isinstance(value, list):
            output[dict2[key]] = walk_list(value, dict2)
        else:
            output[dict2[key]] = value
    return output

def walk_list(sublist, dict2):
    output = []
    for value in sublist:
        if isinstance(value, dict):
            output.append(walk(value, dict2))
        elif isinstance(value, list):
            output.append(walk_list(value, dict2))
        else:
            output.append(value)
    return output