views:

60

answers:

6

I have a dict, { "foo": set(["a", "b"]), "bar": set(["c", "d"]) }, and I'm given an element of one of the two sets and the name of the other set. I need to remove that element. How would I go about doing this? My best attempt so far is this:

keys = dict.keys()
if Element in dict[keys[0]].union(dict[keys[1]]):
  dict[keys[abs(keys.index(Other_Set) - 1)]].remove(Element)

This seems to be a bit excessive, though; is there any way I can improve it?

A: 

How about:

keys = dict.keys()
dict[keys[1 - keys.index(Other_Set)]].discard(Element)

With discard, you don't get a KeyError if the element's not in the set. Thus, you don't need your check (another alternative is to just ignore the KeyError). And 1 - removes the need for the abs.

Matthew Flaschen
A: 
element = "b"
other = "bar"
d = { "foo": set(["a", "b"]), "bar": set(["b", "c"]) }
theSet = d[[s for s in d.iterkeys() if s != other][0]]
theSet.discard(element)
Plumenator
+2  A: 

Try this:

dictionary['foo' if otherset == 'bar' else 'bar'].discard(element)
carl
I like this best. I would just replace remove with discard as Matthew pointed out.
Plumenator
@Plumenator, yep, realized that would be better immediately after. :-)
carl
Since the keys ('foo' and 'bar') are user-inputted, this won't look quite as pretty once implemented, but I like it nonetheless. Thanks for the help. :)
Fraxtil
+1  A: 

This one might suit you if you do not know a priori the names of the keys in dct:

dct={ "foo": set(["a", "b"]), "bar": set(["c", "d"]) }

element='b'
other_set='bar'

for key,value in dct.iteritems():
    if key != other_set:
        value.discard(element)

print(dct)
# {'foo': set(['a']), 'bar': set(['c', 'd'])}
unutbu
+2  A: 

Use a dictionary to look up the other set:

>>> other={'foo':'bar','bar':'foo'}
>>> d = { "foo": set(["a", "b"]), "bar": set(["b", "c"]) }
>>> element = "b"
>>> setname = "bar"
>>> d[other[setname]].discard(element)
>>> d
{'foo': set(['a']), 'bar': set(['c', 'b'])}
Vicki Laidler
A: 

My variation, generic for any number of sets, takes out given item for all the others:

dict_of_sets={'foo':set(['a','b','c']),'bar': set(['d','b','e']),'onemore': set(['a','e','b'])}
givenset,givenitem='bar','b'
otherset= (key for key in dict_of_sets if key != givenset)
for setname in otherset:
  dict_of_sets[setname].discard(givenitem)

print dict_of_sets

"""Output:
{'foo': set(['c', 'a']), 'bar': set(['e', 'b', 'd']), 'onemore': set(['e', 'a'])}
"""
Tony Veijalainen