2

I have this set:

my_set = {'1': {'a'},
          '2': {'b'},
          '3': {'c'}
          }

I need to print the number with the associated letter in the same order as I have defined my_set, then I coded this:

for i in my_set:
    print (i)

but I got only the numbers and after several runs the numbers appears in different sequences like this:

3
2
1

1
3
2

...

What I'm doing wrong?

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
Fernando Barraza
  • 135
  • 1
  • 1
  • 13
  • 4
    A set and a dictionary are examples of hash tables. They have no order. A set has 'keys'. A dictionary has 'key-value pairs'. You have a dictionary. In both cases, the keys are unordered. In your code, i iterates over the keys. If you want order, then use a list. If you want the output order to be the same as the order that you added the keys to the dictionary, then read about OrderDict in the collections module. – LeslieK Nov 20 '16 at 03:24
  • 2
    That is not a set; that is a dictionary. It happens to contain sets as values, though. What you get when you loop over the dictionary are the keys. – HelloGoodbye Jul 22 '17 at 19:56

1 Answers1

0

Try using the dict.items() method.

items() Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.

You can do:

for k, v in my_set.items():
    print(k, v)