Home > Back-end >  How to insert only new key to existing key:value pair dictionary python
How to insert only new key to existing key:value pair dictionary python

Time:07-23

I have a dict as below:

dict1={
       'item1': 
         {'result': 
           [{'val': 228, 'no': 202}]
         }, 
       'item2': 
         {'result':   
           [{'value': 148, 'year': 201}]
         } 
      }

How can we insert a new key 'category' to each item so that the output looks like below:

output={
       'item1': 
        {'category': 
          {'result': 
           [{'val': 228, 'no': 202}]
          }
        }, 
       'item2': 
       {'category':  
         {'result': 
           [{'value': 148, 'year': 201}]
         }
       }
       }

Currently, i have key:value and im looking to insert newkey which takes same value, key:newkey:value

I tried to do dict1['item1']['category1'] but this is adding a new key value pair.

CodePudding user response:

Use to modify in-place the existing dictionary dict1:

for key, value in dict1.items():
    dict1[key] = { "category" : value }

print(dict1)

Output

{'item1': {'category': {'result': [{'val': 228, 'no': 202}]}}, 'item2': {'category': {'result': [{'value': 148, 'year': 201}]}}}

As an alternative use update:

dict1.update((k, {"category": v}) for k, v in dict1.items())

Note that update receives both a dictionary or an iterable of key/value pairs, from the documentation:

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).

Finally in Python 3.9 , you can use the merge operator (|=), as below:

dict1 |= ((k, {"category": v}) for k, v in dict1.items())

CodePudding user response:

Try:

out = {k: {"category": v} for k, v in dict1.items()}
print(out)

Prints:

{
    "item1": {"category": {"result": [{"val": 228, "no": 202}]}},
    "item2": {"category": {"result": [{"value": 148, "year": 201}]}},
}
  • Related