I have a python dictionary. Just to give out context, I am trying to write my own simple cross validation unit.
So basically what I want is to get all the values exc
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.
Also, as a list comprehension using sets:
d = dict(zip(range(9),"abcdefghi"))
blacklisted = [2,5]
outputs = [d[k] for k in set(d.keys())-set(blacklisted)]
Just for fun with sets
keys = set(dict.keys())
excludes = set([...])
for key in keys.difference(excludes):
print dict[key]
keys = ['a', 'b']
a_dict = {'a':1, 'b':2, 'c':3, 'd':4}
[a_dict.pop(key) for key in keys]
After popping out the keys to be discarded, a_dict will retain the ones you're after.
Given a dictionary say
d = {
2: 2, 5: 16, 6: 5,
7: 6, 11: 17, 12: 9,
15: 18, 16: 1, 18: 16,
19: 17, 20: 10
}
then the simple comprehension example would attain what you possibly desire
[v for k,v in d.iteritems() if k not in (2,5)]
This example lists all values not with keys {2,5}
for example the O/P of the above comprehension is
[5, 6, 1, 17, 9, 18, 1, 16, 17, 10]
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]