Using set as a way to reorder iterable

Related searches

I have two tuples a and b and also a dictionary d

a=('C', 'G')
b=('G', 'C') 
d={('G', 'C'): 'T'}

I want d[a] and d[b] to return 'T'.

For that I used set() because I thought that set() was fixing the order of the elements of a iterable object (and removing the duplicates but I don't care about that).

So I did:

tuple(set(a)) in d  # return True
tuple(set(b)) in d  # return True
# I did tuple(set()) because set() alone is not hashable and so cannot be used directly

This works, until it doesn't. And so I discover than sometimes

set(('C', 'G'))
{'C', 'G'}

and sometimes it does not

set(('C', 'G'))
{'G', 'C'}

I understand that set() orders the element as it wants but I expected that the order would always be the same with a given set of elements.

So my questions are:

  • Why it's not the case?
  • How can I solve my initial problem?

Just use sorted tuples whenever you need to index your dict:

a = ('C', 'G')
b = ('G', 'C')
d = {tuple(sorted(a)): 'T'}
for tup in [a, b]:
   print( tup, d[tuple(sorted(tup))] )

Order of elements in a set in java, If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same� Iterable in Python. An iteratable is a Python object that can be used as a sequence. You can go to the next item of the sequence using the next() method. You can loop over an iterable, but you cannot access individual elements directly. It’s a container object: it can only return one of its element at the time.

The set is built on some data structure that offers allows efficient checks of membership. The consequence is that Python loses the original ordering specified in the code when instantiating this structure.

If you really only have the two labels, I would probably just explicitly specify both values.

a=('C', 'G')
b=('G', 'C') 
d={a: 'T', b: 'T'}

To solve a larger version of this problem, you will need to set the value of both order separately. For a larger problem, I would use a comprehension with a double loop

lbls = ['a', 'b', 'c']
{(f, s):'T' for f in lbls for s in lbls if f != s}

Set, (For Sets, this is the same as the values() method.) Set.prototype.values(): Returns a new Iterator object that yields the values for each Use to remove duplicate elements from the array const numbers = [2,3,4,4,2,3,3,4,4,5,5,6� An iterable is something you can loop over. Sequences are a very common type of iterable. Many things in Python are iterables, but not all of them are sequences. An iterator is an object representing a stream of data. It does the iterating over an iterable. You can use an iterator to get the next value or to loop over it.

One solution is to normalize the keys by sorting them. When we look up, we also sort the keys before looking up.


def _normalize(key):
    """ Normalize a key (tuple) by sorting """
    key = tuple(sorted(key))
    return key

class TupleKeyDict(
    def __init__(self, *args, **kwargs):
        temp_dict = dict(*args, **kwargs)
        self.dict = {
            _normalize(key): value
            for key, value in temp_dict.items()

    def __getitem__(self, key):
        value = self.dict[_normalize(key)]
        return value

    def __setitem__(self, key, value):
        self.dict[_normalize(key)] = value

    def __delitem__(self, key):
        del self.dict[_normalize(key)]

    def __iter__(self):
        return iter(self.dict)

    def __len__(self):
        return len(self.dict)

    def __repr__(self):
        return repr(self.dict)
>>> tkd = TupleKeyDict(d)
>>> tkd
{('C', 'G'): 'T'}

>>> tkd['C', 'G']

>>> tkd['G', 'C']

>>> tkd.get(('X', 'Y')) is None

>>> tkd['X', 'C'] = 'cx'
>>> tkd['C', 'X']

We cannot use sets as the keys before sets are mutable (changeable) therefore does not have a constant hash--a requirement for being a key. My approach is to create a specialized dictionary where the keys are sorted tuples which make looking up easier.

The __init__ method takes in everything that you can pass into dict(). The __repr__ method aids debugging. All other methods are there to fulfill the requirements.

How to Use sorted() and sort() in Python – Real Python, To get started with Python sorting, you're first going to see how to sort both numeric Notice how even though the input was a set and a tuple, the output is a list However, if a iterable contains a combination of integers and strings that are all� Let’s see what iterables are and how we can make an object iterable. At the end of this article, you’ll know how to use for-of loop on custom objects, and in this case, on myFavouriteAuthors. Iterables and Iterators. You saw the problem in the previous section. There was no easy way to get all the authors from our custom object.

Java SortedSet, The Java SortedSet interface behaves like a normal Set with the treeSet.add(" two"); treeSet.add("three"); Iterator iterator = treeSet. of a SortedSet according to its sort order by calling the first() method of the SortedSet . new Set (iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set. set.add (value) – adds a value, returns the set itself. set.delete (value) – removes the value, returns true if value existed at the moment of the call, otherwise false.

How to Reorder A Collection With the STL, How to Reorder A Collection With the STL To achieve this, we can define an order on the set of permutations of a given collection. In C++11, std::rotate returns an iterator pointing to the position where the first element has� The numbers_set_sorted value when cast to a set is not ordered, as expected. The other variable, numbers_tuple_sorted, retained the sorted order. Sorting Strings# str types sort similarly to other iterables, like list and tuple.

iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator. reverse (Optional) - If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided. key (Optional) - A function that serves as a key for the sort comparison. Defaults to None.

  • Either use the tuple(sorted(x)) as the key or frozenset(x)
  • I didn't mean this was the exact implementation, just an example of this sort of data structure. Removed the reference.
  • Ah, ok. You meant "e.g." then, not "i.e.".