问题描述
我知道有关访问嵌套字典中的键,值的问题曾经被问过,但是我的以下代码却遇到了一些麻烦:
I know questions regarding accessing key, value in a nested dictionary have been asked before but I'm having some trouble with the following piece of my code:
用于访问嵌套字典的键和值,如下所示:
For accessing the keys and values of a nested dictionary as follows:
example_dict = {'key_outer_01': {'key_inner_01': 'value_inner_01'},
'key_outer_02': {'key_inner_02': 'value_inner_02'}}
我有以下代码:
def get_key_value_of_nested_dict(nested_dict):
for key, value in nested_dict.items():
outer_key = None
inner_key = None
inner_value = None
if isinstance(value, dict):
outer_key = key
get_key_value_of_nested_dict(value)
else:
inner_key = key
inner_value = value
return outer_key, inner_key, inner_value
我得到的输出是:
key_outer_01 None None
我在这里做错了什么?
What am I doing wrong here?
推荐答案
在递归调用中,您将设置 outer_key , inner_key 和 inner_value >到None
.但是在if isintance(value, dict)
中,您仅将 outer_key 重命名为key
.您可能要分配inner_key
和inner_value
的新值.
In your recursive call, you are setting outer_key, inner_key and inner_value to None
. But in the if isintance(value, dict)
, you are only redifining outer_key to key
. You might want to assign the new values of inner_key
and inner_value
.
为inner_key
和inner_value
分配新值!如:
example_dict = {'key_outer_01': {'key_inner_01': 'value_inner_01'},
'key_outer_02': {'key_inner_02': 'value_inner_02'}}
def get_key_value_of_nested_dict(nested_dict):
for key, value in nested_dict.items():
outer_key = None
inner_key = None
inner_value = None
if isinstance(value, dict):
outer_key = key
_, inner_key, inner_value = get_key_value_of_nested_dict(value)
else:
inner_key = key
inner_value = value
return outer_key, inner_key, inner_value
print get_key_value_of_nested_dict(example_dict)
# outputs : ('key_outer_01', 'key_inner_01', 'value_inner_01')
我相信我们需要更多信息,而所有极端情况都需要知道此代码是否正确.
I believe we need more information whereas all the edge-cases to know if this code is good or not.
我尝试了一些改进,告诉我它是否比原始代码更适合您的情况.
I tried for fun some kind of improvement, tell me if it suits your case better than your original code.
example_dict = {'key_outer_01': {'key_inner_01': 'value_inner_01', 'key_inner_02' : 'value_inner_02'},
'key_outer_02': {'key_inner_02': 'value_inner_02'},
'key_outer_03' : None}
def get_k_v_of_inner(nested_dict):
for k, v in nested_dict.items():
if isinstance(v, dict):
for k_nested, v_nested in v.items():
yield {k : {k_nested : v_nested}}
else:
# do_something, or simply ignore if not nested dict.
pass
gen = get_k_v_of_inner(example_dict)
for c, value in enumerate(gen):
print '#{} : {}'.format(c, value)
# outs : #0 : {'key_outer_01': {'key_inner_02': 'value_inner_02'}}
#1 : {'key_outer_01': {'key_inner_01': 'value_inner_01'}}
#2 : {'key_outer_02': {'key_inner_02': 'value_inner_02'}}
这篇关于访问嵌套字典中的键,值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!