[英]Python Nested Dictionary key wise values comparision
我有一本字典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}
與嵌套值val1
, val2
, null
在它們之間進行比較被重新構造為a:{equal: [d,e], null:f}
如果d
, e
值val1
= val2
並且f
是null
值,因此每個鍵都應該具有類似於此格式的值{a:{equal: [], unequal:[], null:[]}}
.
你可以使用它,有點長,但解釋清楚簡單的段落,無論如何都有成千上萬種不同的方法和很多“更優雅”的方法:
### 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例如
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.