LoMaPh
LoMaPh

Reputation: 1690

Python dict key + list removal

Is there a way to make a list of keys of a dict excluding an specific one, in one single command?

Using two commands it can be done:

aDict = {'a': 'cat', 'b': 'dog', 'c': 'cow'}
list1 = aDict.keys()
list1.remove('b')

I'm looking for sth like list1 = aDict.keys().remove('b'). I know this doesn't work, but is there sth that works?

Upvotes: 0

Views: 53

Answers (2)

Blue_vision
Blue_vision

Reputation: 154

What you're probably looking for is a list comprehension:

list1 = [key for key in aDict.keys() if key != 'b']

That said, the right answer might be to just use the example you provide. The Python style guide suggests writing your code to maximize the obviousness of what you are doing. Unless there's a good reason to do it in a one-liner, aim for the longer code that makes your intent clearer.

Upvotes: 1

Kirk Strauser
Kirk Strauser

Reputation: 30933

You can use a list comprehension to filter the results as you iterate across them. For example:

list1 = [key for key in aDict if key != 'b']

would do it.

Upvotes: 3

Related Questions