PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

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

 July 23, 2022     dictionary, json, python     No comments   

Issue

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.


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())


Answered By - Dani Mesejo
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing