ahajib
ahajib

Reputation: 13520

Python Delete a key from a dictionary with multiple keys

So I have a dictionary which looks like the following:

dictionary={('a','b'):1,('c','d'):2}

As you can see there are multiple keys for a value. What I would like to do is basically drop (delete) one of the keys. For example, I want to say that all values will not need the first key anymore and convert the above dictionary to the following:

dictionary={'b':1,'d':2}

What would be the safest way of doing this?

Thanks

Upvotes: 0

Views: 105

Answers (3)

Ajax1234
Ajax1234

Reputation: 71471

In case you have keys that are not lists or tuples, you will want to use this:

d ={('a','b'):1,('c','d'):2}

new_d = {a[-1] if isinstance(a, tuple) or isinstance(a, list) else a:b for a, b in d.items()}

Upvotes: 1

Alexander McFarlane
Alexander McFarlane

Reputation: 11293

I don't like assuming the structure of keys. To make it absolutely bomb-proof

from collections import Iterable
d = {
    k[-1] if isinstance(k, Iterable) else k: v
    for k, v in dictionary.iteritems()
}

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

You can use a dictionary comprehension dropping the first item in each tuple:

dictionary = {k: v for (_, k), v in dictionary.items()}

Upvotes: 8

Related Questions