Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pop many elements from a Python dict

This is my code:

a = dict(aa='aaaa', bb='bbbbb', cc='ccccc', ...)
print(a.pop(['cc', ...]))

but this raises an error. What is the best simple way to pop many elements from a python dictionary?

like image 659
zjm1126 Avatar asked Mar 17 '11 01:03

zjm1126


People also ask

Can you pop from a dictionary Python?

Python Dictionary pop() MethodPython pop() method removes an element from the dictionary. It removes the element which is associated to the specified key. If specified key is present in the dictionary, it remove and return its value.

Does pop work on dict?

The pop() method removes the specified item from the dictionary. The value of the removed item is the return value of the pop() method, see example below.


3 Answers

How about the simple:

for e in ['cc', 'dd',...]: 
  a.pop(e)
like image 90
Himadri Choudhury Avatar answered Oct 17 '22 17:10

Himadri Choudhury


Using list comprehension:

a = {'key1':'value1','key2':'value2','key3':'value3'}
print [a.pop(key) for key in ['key1', 'key3']]
like image 33
Tomek Kopczuk Avatar answered Oct 17 '22 17:10

Tomek Kopczuk


If I understand correctly what you want, this should do the trick:

print [a.pop(k) for k in ['cc', ...]]

Be careful, though, because pop is destructive, i.e. it modifies your dictionary.

like image 5
Vojislav Stojkovic Avatar answered Oct 17 '22 17:10

Vojislav Stojkovic