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'}
}
>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)