Converting a dictionary into a list
dictionary, list, python
Solution
You'll need to use a function to flatten your structure:
def flatten(d):
for key, value in d.iteritems():
yield key
for sub in flatten(value):
yield sub
(The `.iteritems()` should be replaced with `.items()` if you are using Python 3).
On python 3.3 and newer, you can also use the new `yield from` syntax:
def flatten(d):
for key, value in d.items():
yield key
yield from flatten(value)
This will recursively yield all the keys. To turn that into a list use:
list(flatten(elements))
Since Python dictionaries are unordered, the ordering of the keys returned is not going to be sorted. You'll have to explicitly sort the result if you want your keys to have a specific ordering.
Problem
Example: ``` something = { "1": { "2": { "3": { "4": {}, "5": {}, "7": {}, }, "8": { "9": {}, "10": {} }, "11": { "12": { "13": { "14": { "15": { "16": { "17": { "18": {} } } } } } } } } } } ``` I'm trying to convert this dictionary in to a list of items like this: ``` ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18'] ``` What method should I use? I already tried something.items(), but what I got back was: ``` [('1', {'2': {'11': {'12': {'13': {'14': {'15': {'16': {'17': {'18': {}}}}}}}}, '8': {'9': {}, '10': {}}, '3': {'5': {}, '4': {}, '7': {}}}})] ``` This is my first time posting here, so if I did anything wrong please let me know. Thank you and sorry for the weird post.