如何连接嵌套Python字典的值?

4 投票
4 回答
5067 浏览
提问于 2025-04-15 20:58

假设我有一个字典,里面还有字典嵌套在里面。
我想要把这个字典里的所有值都连接起来,递归地进行?

' '.join(d.values())

如果没有嵌套的话,这个方法是有效的。

4 个回答

1

如果配置得当,这个方法也可以用于其他类型的嵌套可迭代对象,而不仅仅是字典:

‘原型’:

def should_iter_fnc(it):
    """returns 'True' if 'it' is viewed as nested"""
    raise NotImplementedError

def join_fnc(itr):
    """transform an iterable 'itr' into appropriate object"""
    raise NotImplementedError

def values_fnc(itr):
    """get the list of 'values' of interest from iterable 'itr'"""
    raise NotImplementedError

这个函数本身

def recursive_join(smth, join_fnc, should_iter_fnc, values_fnc):
    if should_iter_fnc(smth):
        return join_fnc([
                 recursive_join(it, join_fnc, should_iter_fnc, values_fnc)
                 for it in values_fnc(smth)
                 ])
    else:
        return smth

给出:

>>>
def should_iter(it):
    """Returns 'True', if 'it' is 'iterable' but not an 'str' instance"""
    if isinstance(it, str):
        return False
    try:
        iter(it)
        return True
    except TypeError:
        return False

>>> print recursive_join(smth=[['1','2'],['3','4'],'5'],
                     join_fnc=lambda itr: ' '.join(itr),
                     should_iter_fnc=should_iter,
                     values_fnc=list)
1 2 3 4 5
>>> print recursive_join(smth={1:{1:'1',2:'2'},2:{3:'3',4:'4'},3:'5'},
                     join_fnc=lambda itr: ' '.join(itr),
                     should_iter_fnc=should_iter,
                     values_fnc=lambda dct:dct.values())
1 2 3 4 5
4

试试下面这个方法

def flatten(d):
    ret = []

    for v in d.values():
        if isinstance(v, dict):
            ret.extend(flatten(v))
        else:
            ret.append(v)

    return ret

my_dict = {1: 'bar', 5: {6: 'foo', 7: {'cat': 'bat'}}}
assert ' '.join(flatten(my_dict)) == 'bar foo bat'
7

下面的代码适用于任何非递归的嵌套字典:

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'

更新:支持递归字典

如果你需要处理自引用的字典,也就是字典里面有指向自己的情况,你需要对上面的代码进行一些扩展,以便记录所有已经处理过的字典,确保你不会再次处理已经见过的字典。下面的代码是一种相对简单且易于理解的方法:

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'

撰写回答