PenguinPete
PenguinPete

Reputation: 27

Remove a value from a dictionary with multiple values

I've been trying to remove a specific item from multiple values in a dictionary in python and am not completely sure how to do this. For example, in the dictionary:

d  = {('hello', 'hi', 'how are you'): 2, ('hi', 'hello', 'how are you'): 1}

How would I remove 'hi' so that all that remains is:

d  = {('hello', 'how are you'): 2, ('hello', 'how are you'): 1}

Upvotes: 0

Views: 2459

Answers (4)

RocketDonkey
RocketDonkey

Reputation: 37279

Not sure if this works for you, but this creates a new dictionary and will sum the values of any keys that end up colliding after removing 'hi' (assuming that is what you want to do - if not, disregard this answer :) ):

>>> from collections import defaultdict
>>> new_d = defaultdict(int)
>>> for k, v in d.iteritems():
...   new_d[tuple(i for i in k if i != 'hi')] += v
...
>>> new_d
defaultdict(<type 'int'>, {('hello', 'how are you'): 3})

This does not correspond with your output, but as explained by everyone else, dictionaries can only have one key of a particular value, so this combines into one.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114035

This should do it

answer = {}
for k,v in d.iteritems():
    key = tuple(i for i in k if i!='hi')
    answer[key] = v
d = answer

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

You won't get the expected output here, as both keys are now same. So, only one of them can be found in the resulting dict.

In [142]: d  = {('hello', 'hi', 'how are you'): 2, ('hi', 'hello', 'how are you'): 1}

In [143]: {tuple(y for y in x if y!='hi'):d[x] for x in d}
Out[143]: {('hello', 'how are you'): 1}

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318698

You apparently want to change the key. So you simply need to store the corresponding value with the new key and remove the old one. However, in your case creating a new dict is easier since you want to modify every single item.

d2 = {}
for key, value in d.iteritems():
    key = list(key)
    if 'hi' in key:
        key.remove('hi')
    d2[tuple(key)] = value

d2 now contains {('hello', 'how are you'): 1}

As you can see it contains only one value unlike in your example because dicts cannot contain the same key twice.

Upvotes: 3

Related Questions