Flatten a Dictionary
Question Explain
In this question, you are required to write a function or method that can 'flatten' a dictionary. A dictionary in this context refers to a specific data structure also known as a key-value store which is used in programming.
Flattening a dictionary involves turning a dictionary that has dictionaries as its some of its values, into a regular dictionary (All keys are of basic datatype, can't be nested), where composite keys are represented by concatenating the keys of the inner dictionaries with the key of the outer one. The concatenation should be done with periods. This operation must not modify the original dictionary and must return a new dictionary containing the flattened key-value pairs.
The task here will require a good understanding of dictionaries, recursive function calls and string manipulations.
Answer Example 1
For instance, consider this python code, where we have a nested dictionary and we want to flatten it:
def flatten_dict(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep).items())
else:
items.append((new_key, v))
return dict(items)
nested_dictionary = {'key': 3, 'foo': {'a': 5, 'bar': {'baz': 8}}}
print(flatten_dict(nested_dictionary))
In this solution, we iterate over the items in the dictionary. If an item's value is another dictionary, we call the flatten_dict() function again with the present key concatenated as the parent key. If the item's value is not a dictionary, we simply add the item's key and value to the items list. Finally, we convert items
list to a dictionary and return it. It would flatten the nested_dictionary
and produce: {'key': 3, 'foo.a': 5, 'foo.bar.baz': 8}
.
Answer Example 2
Let's consider another example of flattening a dictionary in JavaScript.
function flattenDict(dict, parent = "", result = {}) {
for (let key in dict) {
let newKey = parent ? `${parent}.${key}`: key;
if (typeof dict[key] === 'object' && dict[key] !== null) {
flattenDict(dict[key], newKey, result);
} else {
result[newKey] = dict[key];
}
}
return result;
}
let nestedDictionary = { "key": 3, "foo": { "a": 5, "bar": { "baz": 8 }}};
console.log(flattenDict(nestedDictionary));
This JavaScript implementation works in a similar fashion to the Python one although there are syntax differences. It would flatten the nestedDictionary
and produce: {key: 3, 'foo.a': 5, 'foo.bar.baz': 8}
.