Add a new key value pair to an existing key value pair object in python

Beginner Python. I have a dictionary with a key, and its value is an object (dict), which also has a pair of key values. I want to add a pair of key values ​​to a "child" object.

:

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

I want to add:

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

It seems incredibly common, but I can't find a good way to do this.

+4
source share
4 answers
 somedict = {"foo" : {"bar" : "bars value"} } somedict['foo']['baz'] = 'baz value' 

When Python encounters somedict['foo']['baz'] , it first looks at the value of the bare name somedict . He thinks this is a dict . He then evaluates somedict['foo'] and finds that it is another dict. Then he assigns this dict a new key 'baz' with a value of `baz value' .

+6
source

You can just do

 mydict["foo"]["baz"] = "baz value" 

how in

 >>> mydict = {"foo" : {"bar" : "bars value"}} >>> mydict["foo"]["baz"] = "baz value" >>> mydict {'foo': {'baz': 'baz value', 'bar': 'bars value'}} 
+3
source

This will work without knowing the key-value pairs inside the dic :

 >>> dic = {"foo" : {"bar" : "bars value"}} ... >>> pairs = (("baz", "baz value"),) for k,v in pairs: for k1 in dic: dic[k1][k]= v >>> dic {'foo': {'baz': 'baz value', 'bar': 'bars value'}} 

Another example:

 >>> dic = {"foo" : {"bar" : "bars value"},"bar" : {"bar" : "bars value"} } >>> pairs = (("baz", "baz value"),) for k,v in pairs: for k1 in dic: dic[k1][k]= v ... >>> dic {'foo': {'baz': 'baz value', 'bar': 'bars value'}, 'bar': {'baz': 'baz value', 'bar': 'bars value'}} 
+1
source

Alternative using update() :

def updateChild (d, pk, pair): d ["pk"]. update ((pair))

d is the entire dictionary, pk is the parent key, and pair is the tuple of the child key and update data. This is useful if you already have a couple, as it seems, in the title of the question.

0
source

Source: https://habr.com/ru/post/1490973/


All Articles