How about the simple:
for e in ['cc', 'dd',...]:
a.pop(e)
Answer from Himadri Choudhury on Stack OverflowHow about the simple:
for e in ['cc', 'dd',...]:
a.pop(e)
Using list comprehension:
a = {'key1':'value1','key2':'value2','key3':'value3'}
print [a.pop(key) for key in ['key1', 'key3']]
python - Removing multiple keys from a dictionary safely - Stack Overflow
How do I pop multiple items from a queue? (python)
python - Removing one or multiple keys from a dictionary - Stack Overflow
How do I move keys:{nested_keys:values} from a nested dict to another one?
Using dict.pop:
d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
d.pop(k, None)
Using Dict Comprehensions
final_dict = {key: value for key, value in d.items() if key not in [key1, key2]}
where key1 and key2 are to be removed.
In the example below, keys "b" and "c" are to be removed & it's kept in a keys list.
>>> a
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> keys = ["b", "c"]
>>> print {key: a[key] for key in a if key not in keys}
{'a': 1, 'd': 4}
>>>
Specifically, I am wondering how to take all numbers less than 50 from a queue. I am not having trouble with adding numbers or moving them, but with removing them after they're moved. I am getting the following error: "IndexError: pop index out of range". I'm using VisualStudio Code if that matters.
If d is your dictionary and k the key you want to remove:
d.pop(k)
For example:
d = {"a": 1, "b": 2, "c": 3}
d.pop("a")
print d
# {'c': 3, 'b': 2}
If you want to remove multiple:
for k in lst:
d.pop(k)
If you want to do this non-destructively, and get a new dictionary that is a subset, your best bet is:
s = set(lst)
new_dict = {k: v for k, v in d.items() if k not in s}
You could use k not in lst instead of dealing with set(lst), but using set will be faster if the list of items to remove is long.
>>> d = {"a": 1, "b": 2, "c": 3}
>>> for _ in ['a','c']: del(d[_])
...
>>> d
{'b': 2}