Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting element from python dictionary

Tags:

python

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.

like image 707
user1050619 Avatar asked Jul 06 '26 16:07

user1050619


2 Answers

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

like image 181
Abhijit Avatar answered Jul 09 '26 07:07

Abhijit


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']}
like image 33
mgilson Avatar answered Jul 09 '26 06:07

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!