Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a new key value pair to existing key value pair object in python

Tags:

python

Python beginner here. I have a dictionary with a key and its value is an object (dict) who also has a key value pair. I want to add a key value pair to the 'child' object.

given:

{"foo" : 
    {"bar" : "bars value"}
}

I want to add:

{"foo" : 
    {"bar" : "bar value", 
     "baz" : "baz value" 
    }
}

This seems incredibly common but I can't seem to find a good way to do it.

like image 890
Brad Avatar asked Jul 11 '13 18:07

Brad


1 Answers

somedict = {"foo" : 
    {"bar" : "bars value"}
}

somedict['foo']['baz'] = 'baz value'

When Python encounters somedict['foo']['baz'] it first looks-up the value of the bare name somedict. It finds it is a dict. Then it evaluates somedict['foo'] and finds it is another dict. Then it assigns to this dict a new key 'baz' with value `baz value'.

like image 141
unutbu Avatar answered Oct 24 '22 03:10

unutbu