On 2016-05-25, Daiyue Weng <daiyuew...@gmail.com> wrote: > I want to find the maximal number of elements contained in a nested > dictionary, e.g. > > data = { > 'violations': > { > 'col1': {'err': [elem1, elem2, elem3]}, > 'col2': {'err': [elem1, elem2]} > } > } > > so to find the maximal number of elements in the lists for key 'err' in key > 'col1' and 'col2'. Also key 'violations' may contain many keys (e.g. 'col1' > , 'col2', 'col3' etc), so what's the best way to do this (using a loop)? > > max = 0for col in data.violations: > if max < len(data.violations.col.err): > max = len(data.violations.col.err)
In Python 3 you could do: max((len(col["err"]) for col in data["violations"].values()), default=0) In Python 2 you can do the same but you can't specify "default=0" and so it will throw an exception if there are no lists found, so you could use something like: max_errs = 0 if data["violations"]: max_errs = max(len(col["err"]) for col in data["violations"].values()) -- https://mail.python.org/mailman/listinfo/python-list