Python嵌套字典键明智值比较

时间:2019-06-17 03:42:30

标签: python python-3.x

我有字典 d = { a:{d:val1, e:val2, f:null}, b:{p:val3, q:val4, r:val5 }}

因此,我想获取每个键的值,并将它们之间的嵌套键值进行比较,并且需要形成一个新的字典,如下所示: new_dict={a:{equal: [d,e],unequal:[], null:f}, b:{equal:[p,q], unequal:r, null:[]}}

表示a的对应值{d:val1, e:val2, f:null}和嵌套值val1val2null在它们之间进行了比较,并重新构建为{{ 1}}如果a:{equal: [d,e], null:f}d的值e = val1val2是一个f的值,那么每个键都应具有类似于此格式null的值。

1 个答案:

答案 0 :(得分:0)

您可以使用它,虽然时间稍长,但有清晰且简单的说明段落,反正有成千上万种不同的方式使用,并且有很多“更优雅”的方式:

### dictionary in your example
d = { "a":{"d":"val1", "e":"val2", "f":"null"}, "b":{"p":"val3", "q":"val4", "r":"val5" }}
### new dictionary to fill with the results
compared = {}

### open loop on key, value elementd of your dict
for k, v in d.items() :
    ### open a new dict to store the equals, unequals, nulls
    subcompared = {}
    ### open the lists to store the elements
    equals = []; unequals = []; nulls = [];
    ### open loop on k,v items of the subdictionary in your dict
    for sub_k, sub_v in v.items() :
        ### take the first 3 letters of the value (assuming your comparison what kind of it) 
        sub_v_start = sub_v[0:2]
        ### IF null put in list and skip to next iteration 
        if sub_v == "null" :
            nulls.append( sub_k )
            continue
        ### open another loop on the subdictionaries of the dict
        for sub_k2, sub_v2 in v.items() :
            ### if same value of the outer loop skip to net iteration
            if sub_k2 == sub_k or sub_v2 == "null" :
                continue
            else :
                ### if same first 3 letters of the subvalue
                if sub_v2.startswith(sub_v_start) :
                    ### if not in list put the keys in list (a simple way to avoid suplication, you could also use SET after etc.)
                    if sub_k not in equals :
                        equals.append( sub_k )
                    if sub_k2 not in equals :
                        equals.append( sub_k2 )
                ### if first 3 letters differents the same for unequals
                else :
                    if sub_k not in unequals :
                        unequals.append( sub_k )
                    if sub_k2 not in unequals :
                        unequals.append( sub_k2 )
    ### put the lists as values for the relative keys of the subdictionary renewed at every outest loop
    subcompared["equals"] = equals
    subcompared["unequals"] = unequals
    subcompared["nulls"] = nulls
    ### put the subdictionary as value for the same KEY value of the outest loop in the compared dict
    compared[k] = subcompared

### print results
compared
{'b': {'unequals': [], 'equals': ['q', 'r', 'p'], 'nulls': []}, 'a': {'unequals': [], 'equals': ['e', 'd'], 'nulls': ['f']}}

如果您希望以特定方式对新字典的键进行排序,则可以使用OrderedDict例如