Flatten A Nested Dictionary That Contains Lists
Description:
Task
Your task is to create a function that takes a (possibly nested) dictionary as input and returns a second "flattened" dictionary as an output.
A "flattened" dictionary is a dictionary who's keys are a string of the nested keys for each dictionary "endpoint", seperated by a "." character. By this definition, a flattened dictionary cannot be nested (i.e. every "value" in the dictionary is not a dictionary itself).
For instance, the following dictionary:
{
"a": {
"b": {"c": 1, "d": 2},
"e": 3
},
"f": 4
}
would "flatten" into:
{'a.b.c': 1, 'a.b.d': 2, 'a.e': 3, 'f': 4}
Additionally, your function should be able to handle nested dictionaries where some of the keys are lists of dictionaries (these keys can occur at any level of nesting). In this case, the "key" is considered to be the index/position of each dictionary in the list, and this key should be enclosed in list brackets ('[' and ']').
For instance, the following dictionary:
d = {
"a": {
"b": {"c": 1, "d": 2},
"e": 3
},
"f": 4,
"g": [
{"h": 5},
{
"i": 6,
"j": [
{"k": 7},
{"l": 8}
],
}
]
}
would flatten to:
{
'a.b.c': 1,
'a.b.d': 2,
'a.e': 3,
'f': 4,
'g[0].h': 5,
'g[1].i': 6,
'g[1].j[0].k': 7,
'g[1].j[1].l': 8}
}
Caveats
- The nested dictionary structure may contain empty-lists and empty-dictionaries, though these will always be at endpoints.
- All nested keys will be hashable, though the values at the end-points may not be, i.e.:
is valid, because{ 'a': { 'b': [] } }
'a'
and'b'
are both hashable, and empty-lists are not but the empty-list is an endpoint. In this case, the above dictionary wouldflatten
to become:{ 'a.b': [] }
- An empty dictionary
flatten
s into another empty dictionary
Good luck!
Similar Kata:
Stats:
Created | May 17, 2019 |
Published | Sep 3, 2019 |
Warriors Trained | 392 |
Total Skips | 58 |
Total Code Submissions | 552 |
Total Times Completed | 48 |
Python Completions | 48 |
Total Stars | 9 |
% of votes with a positive feedback rating | 77% of 28 |
Total "Very Satisfied" Votes | 17 |
Total "Somewhat Satisfied" Votes | 9 |
Total "Not Satisfied" Votes | 2 |
Total Rank Assessments | 17 |
Average Assessed Rank | 6 kyu |
Highest Assessed Rank | 5 kyu |
Lowest Assessed Rank | 7 kyu |