【发布时间】:2020-04-26 22:52:28
【问题描述】:
res_dict = {}
def get_value(co , passed_dict ):
for k, v in passed_dict.items():
if isinstance(v, dict):
get_value(co, v)
else:
res_dict[k] = v
print("from else",res_dict)
return res_dict
def easy():
inner_dict = {
"test1" : {"test1_in" : "abc"},
"test2" : {"test1_in" : "xyz"}
}
dict1 = {}
count = 0
val_from_function= {}
key_list = ['key1','key2']
for key in key_list:
count = count + 1
val_from_function = get_value(count ,inner_dict)
print("before assign" ,dict1 )
dict1[key] = val_from_function
print("after assign" , dict1)
# dict1['key1'] = {'test1' : "abc"}
# dict1['key2'] = {'test1' : "xyz"}
print(dict1)
easy()
- 接收输出:{'key1': {'test1_in': 'xyz'}, 'key2': {'test1_in': 'xyz'}}
预期 o/p : {'key1': {'test1_in': 'abc'}, 'key2': {'test1_in': 'xyz'}}
我了解 dict1 的值已更新为 res_dict 声明为全局的最后一个值 多变的。
- 我可以通过将内部键值附加到外部键然后存储在字典中来解决它。
- 我可能会使用有序字典来解决它。
- 将列表中的键作为外部键值 (key1, key2 ..,key3000) 未知。
寻找有关如何使用预期的 o/p 使此代码更好的建议。 有 3k 个密钥对值,与具有更多嵌套 k、v 和将 o/p 存储为缓存的示例模式相同,因此这里的性能不是一个很大的问题。
【问题讨论】:
标签: python-3.x recursion