for key, value in your_dict.items():
if key not in your_blacklisted_set:
print value
the beauty is that this pseudocode example is valid python code.
it can also be expressed as a list comprehension:
resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]
Answer from Samus_ on Stack Overflowpython - Return copy of dictionary excluding specified keys - Stack Overflow
Copy a dictionary, except some keys - #1000 - Ideas - Discussions on Python.org
python - Compare dictionaries ignoring specific keys - Stack Overflow
methods - Remove key from dictionary in Python returning new dictionary - Stack Overflow
for key, value in your_dict.items():
if key not in your_blacklisted_set:
print value
the beauty is that this pseudocode example is valid python code.
it can also be expressed as a list comprehension:
resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]
If your goal is to return a new dictionary, with all key/values except one or a few, use the following:
exclude_keys = ['exclude', 'exclude2']
new_d = {k: d[k] for k in set(list(d.keys())) - set(exclude_keys)}
where 'exclude' can be replaced by (a list of) key(s) which should be excluded.
You were close, try the snippet below:
>>> my_dict = {
... "keyA": 1,
... "keyB": 2,
... "keyC": 3
... }
>>> invalid = {"keyA", "keyB"}
>>> def without_keys(d, keys):
... return {x: d[x] for x in d if x not in keys}
>>> without_keys(my_dict, invalid)
{'keyC': 3}
Basically, the if k not in keys will go at the end of the dict comprehension in the above case.
In your dictionary comprehension you should be iterating over your dictionary (not k , not sure what that is either). Example -
return {k:v for k,v in d.items() if k not in keys}
def equal_dicts(d1, d2, ignore_keys):
d1_filtered = {k:v for k,v in d1.items() if k not in ignore_keys}
d2_filtered = {k:v for k,v in d2.items() if k not in ignore_keys}
return d1_filtered == d2_filtered
EDIT: This might be faster and more memory-efficient:
def equal_dicts(d1, d2, ignore_keys):
ignored = set(ignore_keys)
for k1, v1 in d1.iteritems():
if k1 not in ignored and (k1 not in d2 or d2[k1] != v1):
return False
for k2, v2 in d2.iteritems():
if k2 not in ignored and k2 not in d1:
return False
return True
Using dict comprehensions:
>>> {k: v for k,v in d1.items() if k not in ignore_keys} == \
... {k: v for k,v in d2.items() if k not in ignore_keys}
Use .viewitems() instead on Python 2.
How about this:
{i:d[i] for i in d if i!='c'}
It's called Dictionary Comprehensions and it's available since Python 2.7.
or if you are using Python older than 2.7:
dict((i,d[i]) for i in d if i!='c')
Why not roll your own? This will likely be faster than creating a new one using dictionary comprehensions:
def without(d, key):
new_d = d.copy()
new_d.pop(key)
return new_d
First of all, Im a beginner, so please explain it simple.
for example we have a dictionary of keys like username and password and gmail and some values, I want to print all the keys and values except password key. so what should I write?
I've tried this but it won't work.
information = {
"Username" : "Guest",
"Password" : "Guest1234",
"Gmail" : "Guest1234@gmail.com",
"Gender" : "Unknown",
"Phone" : 123456789
}
for x,y in information.items():
print(x,y except "Password")
Hi All
The title is a bit of a mess so Ill explain, heres a dictionary
asdf = {
"a": 1,
"b": 2,
"c": 3,
}
but lets say I want the "b" key to be conditionally added based on some other variable foo
If I do this
asdf = {
"a": 1,
"b": 2 if foo else None,
"c": 3,
}
If foo is False, then the output is
{
"a": 1,
"b": None,
"c": 3,
}But I want to exclude the key and value and get this output
{
"a": 1,
"c": 3,
}Is there any way of doing this inline and not having to something like this
asdf = {
"a": 1,
"c": 3,
}
if foo:
asdf["b"] = 2Constructing a new dict:
dict_you_want = {key: old_dict[key] for key in your_keys}
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}