Python 从两个集合的dict中的另一个集合中删除给定的元素

Python 从两个集合的dict中的另一个集合中删除给定的元素,python,dictionary,set,Python,Dictionary,Set,我有一个dict,{“foo”:set([“a”,“b”]),“bar”:set([“c”,“d”])},我得到了两个集合中的一个元素和另一个集合的名称。我需要删除该元素。我该怎么做呢?到目前为止,我最好的尝试是: keys = dict.keys() if Element in dict[keys[0]].union(dict[keys[1]]): dict[keys[abs(keys.index(Other_Set) - 1)]].remove(Element) 不过,这似乎有点过分;

我有一个dict,
{“foo”:set([“a”,“b”]),“bar”:set([“c”,“d”])}
,我得到了两个集合中的一个元素和另一个集合的名称。我需要删除该元素。我该怎么做呢?到目前为止,我最好的尝试是:

keys = dict.keys()
if Element in dict[keys[0]].union(dict[keys[1]]):
  dict[keys[abs(keys.index(Other_Set) - 1)]].remove(Element)
不过,这似乎有点过分;有什么办法可以改进吗?

怎么样:

keys = dict.keys()
dict[keys[1 - keys.index(Other_Set)]].discard(Element)
使用
discard
,如果元素不在集合中,则不会得到
KeyError
。因此,您不需要检查(另一种选择是忽略
键错误
)。并且
1-
不再需要
abs

尝试以下方法:

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)
dictionary['foo' if otherset == 'bar' else 'bar'].discard(element)

如果您事先不知道
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'])}

使用字典查找其他集合:

>>> 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'])}

我的变体,对于任意数量的集合都是通用的,对于所有其他集合,都会取出给定的项:

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'])}
"""
这是一种更为“蟒蛇式”的方式:

当然
d['foo']
可以是
d[hashable\u key]
,hashable\u key有用户输入,或者你有什么

集合上的&^ |被重载为以下各自的变异方法:

a_set.difference_update(other_set) # also "-"
a_set.intersection_update(other_set) # also "&"
a_set.symmetric_difference_update(other_set) # also "^"
a_set.update(other_set) # also "-"
然后,您可以使用增广赋值
-=
修改“foo”的设置值。这里提供的所有其他解决方案对我来说都太罗嗦了


编辑我误读了OP,并将其作为答案忽略。我投了赞成票

我最喜欢这个。正如马修所指出的,我会用丢弃来代替移除。@Plumenator,是的,他意识到这会在之后立即变得更好。:-)由于键('foo'和'bar')是用户输入的,一旦实现,看起来就不那么漂亮了,但我还是喜欢它。谢谢你的帮助。:)@普卢门纳特:我误读了OP,把重点放在了两组之间的差异上。很抱歉
a_set.difference_update(other_set) # also "-"
a_set.intersection_update(other_set) # also "&"
a_set.symmetric_difference_update(other_set) # also "^"
a_set.update(other_set) # also "-"