Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert only new key to existing key:value pair dictionary python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading