Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain all entries except for one key python

Tags:

python

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 except for the given keys. And depending on the input, it returns all the values from a dictionary except to those what has been given.

So if the input is 2 and 5 then the output values doesn't have the values from the keys 2 and 5?

like image 595
frazman Avatar asked Jan 03 '12 19:01

frazman


People also ask

Can you have multiple values for one key in Python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

Does Python dictionary keys maintain order?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

What does .items do in Python?

The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

How do you check if a key exists in a dictionary Python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.


1 Answers

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] 
like image 131
Samus_ Avatar answered Sep 18 '22 12:09

Samus_