Suppose I have a dictionary, and it's nested with dictionaries inside. I want to join all the values of that dictionary, recursively?
' '.join(d.values())
That works if there are no nests.
The following works for any non-recursive nested dicts:
def flatten_dict_values(d):
values = []
for value in d.itervalues():
if isinstance(value, dict):
values.extend(flatten_dict_values(value))
else:
values.append(value)
return values
>>> " ".join(flatten_dict_values({'one': 'not-nested',
... 'two': {'three': 'nested',
... 'four': {'five': 'double-nested'}}}))
'double-nested nested not-nested'
Edit: Support for recursive dicts
If you need to support self-referencing dicts, you need to extend the above code to keep track of all processed dicts and make sure you never attempt to process a dictionary that you've already seen. The following is a reasonably cheap, yet readable way to do it:
def flatten_dict_values(d, seen_dict_ids=None):
values = []
seen_dict_ids = seen_dict_ids or set()
seen_dict_ids.add(id(d))
for value in d.itervalues():
if id(value) in seen_dict_ids:
continue
elif isinstance(value, dict):
values.extend(flatten_dict_values(value, seen_dict_ids))
else:
values.append(value)
return values
>>> recursive_dict = {'one': 'not-nested',
... 'two': {'three': 'nested'}}
>>> recursive_dict['recursive'] = recursive_dict
>>> " ".join(flatten_dict_values(recursive_dict))
'nested not-nested'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With