我有一本这样的字典:
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是如何保持不变的。我不知道如何做到这一点优雅,所以任何帮助将不胜感激
我会用递归来做:
这应该适用于任意深度嵌套,包括在列表元素内(例如,如果第n个列表元素本身是包含更多dict/列表的dict)
单线解决方案可能如下所示:
注意,我用字符串替换了键和列表的值
您可以尝试:
它返回:
相关问题 更多 >
编程相关推荐