I need the most efficient way to delete few items from the dictionary, RIght now, Im using for stmt as given below..Thinking the same thing should be accomplished in few lines.
for eachitem in dicta:
del eachitem['NAME']
del eachitem['STATE']
del eachitem['COUNTRY']
del eachitem['REGION']
del eachitem['LNAME']
dicta = [{'name','Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian',Salary:6000}]
I want only the salary item in the dictionary once its deleted. Any inputs are appreciated.
If your example data is what you are dealing with, instead of deleting the elements, just recreate your dict with that lone key
dicta = [{'Salary':e['Salary']} for e in dicta]
or to me, it makes more sense, to just create a list instead of list of dicts
dicta = [e['Salary'] for e in dicta]
but depends on what you are planning to achieve
I suppose you could use:
for eachitem in dicta:
for k in ['NAME','STATE','COUNTRY','REGION','LNAME']:
del eachitem[k]
Or, if you only want 1 key:
for eachitem in dicta:
salary = eachitem['SALARY']
eachitem.clear()
eachitem['SALARY'] = salary
This does everything in place which I assume you want -- Otherwise, you can do it out of place simply by:
eachitem = {'SALARY':eachitem['SALARY']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With