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'}}
I have the following piece of code:
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
The output that I'm getting is:
key_outer_01 None None
What am I doing wrong here?
Output:
One thing for sure is you need a
return
hereIf you have a nested
dict
, you need a nestedfor
loop:This prints:
You get a list of tuples. In each tuple the first element is a list of your keys and the second is the final value.
To simply get a list of tuples with no inner list of keys just change the function a bit:
In your recursive call, you are setting outer_key, inner_key and inner_value to
None
. But in theif isintance(value, dict)
, you are only redifining outer_key tokey
. You might want to assign the new values ofinner_key
andinner_value
.Assign new value to
inner_key
andinner_value
! Such as :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.