0 votes
1 view
in Python by (11.2k 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 (22.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)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 27 in Python by Sammy (47.7k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...