Count Keys

Run Settings
LanguagePython
Language Version
Run Command
""" This counts the number of occurrences of a second-level key within an input dict. All operations run in O(n) time. """ def makeProfiles (v, c={}): # initialize a list of keys keylist = list() # for each first-level key in v, get all of its child keys for key in v: keylist += list(v[key].keys()) # create a set so that we remove duplicates and can iterate through keys faster keyset = set(keylist) # for each key in the set of keys, find the number of that key's occurrences in keylist for key in keyset: c[key] = keylist.count(key) return c v = { "001": { "1": "a" }, "002": { "1": "b" }, "003": { "2": "c" }, "004": { "2": "d" } } print(makeProfiles(v))
Editor Settings
Theme
Key bindings
Full width
Lines