1

Here is a better explanation, I have a list of keys of a dict:

keys_list = ['one', 'two', 'three']

and my dict is:

my_dict = {'one':{'two': {'three': 'three_value'}, 'some': 'some_value'}, 'next': 'next_value'}

I would actually like my code to traverse through the list to get the value associated with the last key, as such

print(my_dict['one']['two']['three'])
# Output: three_value

If the keys_list changed to:

keys_list = ['next']

It would search

print(my_dict['next'])
# Output: next_value

My current solution

import copy
copied_dict = copy.deepcopy(my_dict)
for key in keys_list:
    copied_dict = copied_dict[key]
print(copied_dict)

It is bad, I know and would love a simpler solution.

piyush daga
  • 501
  • 4
  • 17

0 Answers0