I have a question about this coding challenge for "Flatten a Dictionary":
Given a dictionary dict, write a function flattenDictionary that returns a flattened version of it .
If you’re using a compiled language such Java, C++, C#, Swift and Go, you may want to use a Map/Dictionary/Hash Table that maps strings (keys) to a generic type (e.g. Object in Java, AnyObject in Swift etc.) to allow nested dictionaries.
Example:
Input:
dict = { "Key1" : "1", "Key2" : { "a" : "2", "b" : "3", "c" : { "d" : "3", "e" : "1" } } }
Output:
{ "Key1" : "1", "Key2.a" : "2", "Key2.b" : "3", "Key2.c.d" : "3", "Key2.c.e" : "1" }
Important: when you concatenate keys, make sure to add the dot character between them. For instance concatenating Key2, c and d the result key would be Key2.c.d.
def flatten_dictionary(dictionary):
def items():
# loop through each item inside the dictionary k, v
#Appending
# check if the sub-key and sub-value are
# inside the flatten_dict(value)
# join on subkey array
# add to result
# clear out prev_keys
for key, value in dictionary.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_dictionary(value).items():
if key == "":
yield subkey, subvalue
yield key + "." + subkey, subvalue
else:
yield key, value
return dict(items())
# test cases 1
dictionary2 = {
"Key1" : "1",
"Key2" : {
"a" : "2",
"b" : "3",
"c" : {
"d" : "3",
"e" : "1"
}
}
}
# output: {
# "Key1" : "1",
# "Key2.a" : "2",
# "Key2.b" : "3",
# "Key2.c.d" : "3",
# "Key2.c.e" : "1"
# }
print(flatten_dictionary(dictionary2))
dict
behaves likeOrderedDict
), so you can't definitively say across python versions how it should behave. Yourkey + '.' + subkey
also doesn't generalize, but keys are not always strings. Anything immutable that defines__hash__
and__eq__
can be a key. \$\endgroup\$