Skip to content

Instantly share code, notes, and snippets.

@willwangcc
Created June 6, 2018 22:49
Show Gist options
  • Save willwangcc/ae4b7273450ca7377c1be90fdde396c3 to your computer and use it in GitHub Desktop.
Save willwangcc/ae4b7273450ca7377c1be90fdde396c3 to your computer and use it in GitHub Desktop.
# Time: O(N) where N is the number of keys in the input dictionary
# Space: O(N) since the ouput dict is asymptotically as big as the input dict
def flatten_dictionary(dictionary):
pass # your code goes here
flat_dict = {}
flat_dict_helper("", dictionary, flat_dict)
return flat_dict
def flat_dict_helper(inital_key, dictionary, flat_dict):
for key in dictionary.keys():
val = dictionary.get(key)
if not isinstance(val, dict):
if inital_key == None or inital_key == "":
flat_dict[key] = val
else:
flat_dict[inital_key + "." + key] = val
else:
if inital_key == None or inital_key == "":
flat_dict_helper(key, val, flat_dict)
else:
flat_dict_helper(inital_key + "." + key, val, flat_dict_helper)
dictionary = {
"Key1" : "1",
"Key2" : {
"a" : "2",
"b" : "3",
"c" : {
"d" : "3",
"e" : {
"" : "1"
}
}
}
}
print flatten_dictionary(dictionary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment