Quick actions

cmd+k|ctrl+k

Navigation

Languages

Count Keys

Snippet info

Language

Python

Visibility

public

Author

apizzimenti

Created

2016-11-17T00:31:59Z

Updated

2016-11-17T01:16:00Z


"""
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))
INFO