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

python how to update dictionary object with selected Tags only

How can I update the dictionary object to get selected Tags only. For example in below I only want to get Id, and Locations

InputString: 
{
1235 : {'Id':1, 'Product' : 'Prod1, 'Location' : 'NY'},
1236 : {'Id':2, 'Product' : 'Prod2, 'Location' : 'NJ'}
1237 : {'Id':3, 'Product' : 'Prod3, 'Location' : 'CT'}
}

Result

OutputString: 
{
1235 : {'Id':1, 'Location' : 'NY'},
1236 : {'Id':2, 'Location' : 'NJ'}
1237 : {'Id':3, 'Location' : 'CT'}
}

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

>Solution :

You can use dict comprehensions like so:

InputString= {1235 : {'Id':1, 'Product' : 'Prod1', 'Location' : 'NY'}, 1236 : {'Id':2, 'Product' : 'Prod2', 'Location' : 'NJ'}, 1237 : {'Id':3, 'Product' : 'Prod3', 'Location' : 'CT'}}
OutputString = {d: {k: v for k,v in InputString[d].items() if k in ['Id', 'Location']} for d in InputString}
print(OutputString)

Output:

{1235: {'Id': 1, 'Location': 'NY'}, 
1236: {'Id': 2, 'Location': 'NJ'}, 
1237: {'Id': 3, 'Location': 'CT'}}

You can also make a list of the keys you would like to keep and easily update it to get various combinations:

wanted = ['Id', 'Location']
InputString= {1235 : {'Id':1, 'Product' : 'Prod1', 'Location' : 'NY'}, 1236 : {'Id':2, 'Product' : 'Prod2', 'Location' : 'NJ'}, 1237 : {'Id':3, 'Product' : 'Prod3', 'Location' : 'CT'}}
OutputString = {d: {k: v for k,v in InputString[d].items() if k in wanted} for d in InputString}
print(OutputString)
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