Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I join the values of nested Python dictionary?

Tags:

python

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.

like image 825
TIMEX Avatar asked Dec 18 '22 01:12

TIMEX


1 Answers

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'
like image 115
Pär Wieslander Avatar answered Dec 19 '22 16:12

Pär Wieslander