How do I check value in a nested dictionary in Python? -
suppose have list of dictionaries listd each dictionary quite nested more dictionaries. e.g.suppose first element of listd is:
listd[0] = {"bar1":{"bar2":{"bar3":1234}}} now want check if listd[i]["bar1"]["bar2"]["bar3"] == 1234 i. first element = 0, easy can use expression:
listd[0]["bar1"]["bar2"]["bar3"] == 1234 but cannot write loop like:
for dictelem in listd: if dictelem["bar1"]["bar2"]["bar3"] == 1234: print "equals 1234" this because of dictionary elements of listd might of form
listd[i] = {"bar1":{"bar2":"abcd"}} or listd[i] = {"bar1":{"bar2":none}} and if try access "bar3" when doesn't exists, error raised.
right manually specifying in code check existence of bar1, bar2 , bar3 keys , whether in fact dictionaries or not. verbose , i'm quite sure there's simpler way can't figure out how.
def dictcheck(d, p, v): if len(p): if isinstance(d,dict) , p[0] in d: return dictcheck(d[p[0]], p[1:], v) else: return d == v you pass 1 dict d, 1 path of keys p, , final value check v. recursively go in dicts , check if last value equal v.
>>> dictcheck({"bar1":{"bar2":{"bar3":1234}}}, ('bar1','bar2','bar3'), 1234) true >>> dictcheck({"bar1":1234}, ('bar1','bar2','bar3'), 1234) false so, answer question (i want check if listd[i]["bar1"]["bar2"]["bar3"] == 1234 i):
all(dictcheck(x, ('bar1','bar2','bar3'), 1234) x in listd)
Comments
Post a Comment