Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

Given a path(keys) in list, need to add value to given dictionary

data = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}}

path_to_add = ['personal_information', 'address': 'state']

value = 'Delhi'

expected_output = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}, 'address': {'state': 'Delhi'}}

1 Answer

0 votes
by (25.1k points)

You can use recursion for this. Like this:

data = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}}

path_to_add = ['personal_information', 'address', 'state']

value = 'Delhi'

def addValue(dictionary, path, value):

    if len(path) > 1:

        if path[0] not in dictionary.keys():

            dictionary[path[0]] = {}

        addValue(dictionary[path[0]], path[1:], value)

    else:

        dictionary[path[0]] = value

print(data)

addValue(data, path_to_add, value)

print(data)

If you are interested to learn Python from Industry experts, you can sign up for this Python Certification Course by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 27, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.9k answers

500 comments

693 users

Browse Categories

...