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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With