返回嵌套字典中所有列表中第n个值的字典,并保留其他值

2024-09-30 12:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典:

dict_in = {'key0': {a: [A, B, C], b: [A, B, C]}, 'key1': {c: [A, B, C], d: [A, B, C]}, 'key2': {e: 0, f: 0}}

我想要一个返回相同字典但不包含列表的函数(或任何函数)。代替列表的是一个值,该值对应于每个列表中的第n个值。对于没有相应列表的键,我只希望值保持不变。例如,某些功能本身:

nth_val = 2
def take_nth_value_from_lists_in_nested_dict(list_in, nth_val):
    ...things and stuff...
    return dict_out
dict_out = {'key0': {a: B, b: B}, 'key1': {c: B, d: B}, 'key2': {e: 0, f: 0}}

请注意键2是如何保持不变的。我不知道如何做到这一点优雅,所以任何帮助将不胜感激


Tags: 函数in功能列表字典defvalout
3条回答

我会用递归来做:

def take_nth_value_from_lists_in_nested_dict(obj, n: int):
    if isinstance(obj, dict):
        return {k: take_nth_value_from_lists_in_nested_dict(v, n) for k, v in obj.items()}
    if isinstance(obj, list):
        return take_nth_value_from_lists_in_nested_dict(obj[n-1], n)
    return obj
>>> take_nth_value_from_lists_in_nested_dict({'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C'], 'key1': {'c': ['A', 'B', 'C'], 'd': ['A', 'B', 'C']}, 'key2': {'e': 0, 'f': 0}}, 2)
{'a': 'B', 'b': 'B', 'key1': {'c': 'B', 'd': 'B'}, 'key2': {'e': 0, 'f': 0}}

这应该适用于任意深度嵌套,包括在列表元素内(例如,如果第n个列表元素本身是包含更多dict/列表的dict)

单线解决方案可能如下所示:

list_in = {'key0': {'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C']}, 'key1': {'c': ['A', 'B', 'C'], 'd': ['A', 'B', 'C']}, 'key2': {'e': 0, 'f': 0}}
nth = 1
list_out = {k: {k2: v2 if not isinstance(v2,list) else v2[nth] \
               for k2,v2 in v.items() } \
               for k,v in list_in.items() }

print list_out
{'key2': {'e': 0, 'f': 0}, 'key1': {'c': 'B', 'd': 'B'}, 'key0': {'a': 'B', 'b': 'B'}}

注意,我用字符串替换了键和列表的值

您可以尝试:

list_in = {'key0': {'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C']}, 'key1': {'c': ['A', 'B', 'C'], 'd': ['A', 'B', 'C']}, 'key2': {'e': 0, 'f': 0}}
nth = 1
for k,v in list_in.items():
    for k2 in v.keys():
        element = list_in[k][k2]
        if isinstance(element, list):
            list_in[k][k2] = element[nth]
print(list_in)

它返回:

{'key0': {'a': 'B', 'b': 'B'},
 'key1': {'c': 'B', 'd': 'B'},
 'key2': {'e': 0, 'f': 0}}

相关问题 更多 >

    热门问题