Reputation: 632
Here an example of my set, which I would like to update:
>>> x = set()
>>> x.add(('A1760ulorenaf0821x151031175821564', 1, 0))
>>> x
set([('A1760ulorenaf0821x151031175821564', 1, 0)])
My expected result would be:
set([('A1760ulorenaf0821x151031175821564', 1, 1)])
How I can do it? Is a set is the best option, or have I to use another data structure for that? I thought that update method in set
can do that. However, I made mistake, and that is not a good solution as it does not consider the first parameter as a key and repeat the elements.
Upvotes: 5
Views: 13350
Reputation: 1173
You are better off using a dict
if you are trying to have keys and values and you want to update based on key:
x = {'A1760ulorenaf0821x151031175821564' : [1, 0]}
x['A1760ulorenaf0821x151031175821564'] = [1, 1]
Upvotes: 2
Reputation: 1121486
You'll have to remove the element from the set, and add a new element with that value updated. That's because sets use hashing to efficiently eliminate duplicates. If mutating the elements directly was allowed you'd break this model.
I think you only want the first element to be unique, and track some data associated with that first element. If so you want to use a dictionary instead; use the first element as a key to map to the other two values, in a list for easy altering:
>>> x = {}
>>> x['A1760ulorenaf0821x151031175821564'] = [1, 0]
>>> x['A1760ulorenaf0821x151031175821564'][1] += 1 # increment the second element.
>>> x
{'A1760ulorenaf0821x151031175821564': [1, 1]}
Keys in a dictionary also must be unique.
Note that set.update()
only gives you a union operation; the set is updated in-place by adding all elements from the argument(s) that are not already in the set. set.update()
cannot alter elements already in the set, because elements the set should not be altered (or at least not in ways that change their hash and equality).
Upvotes: 8