3

What this program should do is traverse the array using two loops and take everything in the first set that isn't a number and make it into a key. The keys aren't being added to the dictionary in the order I would expect. There's more to the class but here is the part that is giving me troubles.

class Sorter(): 
def __init__(self, vals): 
    self.vals = vals

def borda(self): 
    bordaContainer = { }
    arrayLength = len(self.vals) 
    for outsides in range(arrayLength):
        for insides in range(len(self.vals[outsides])):
            currentChoice = self.vals[outsides][insides]
            if outsides ==0 and insides != len(self.vals[outsides])-1:
                bordaContainer[currentChoice] = ''
    return bordaContainer

inputArray = [['A','B','C','D',10],['C','D','B','A',4],['D','A','B','C',7]]
first = Sorter(inputArray)
print first.borda()

The result:

{'A': '', 'C': '', 'B': '', 'D': ''} 

I should be getting {'A': '', 'B': '', 'C': '', 'D': ''}. Any explanation to what is happening would be great, thank you!

user3163789
  • 63
  • 2
  • 6
  • Dictionaries in python aren't ordered. Use `OrderedDict` from the `collections` module if you need them to be. – tzaman Sep 03 '15 at 21:17
  • Dictionaries in python do not retain the order in which the keys were inserted. If you do want to maintain an order, try using `OrderedDict`. https://docs.python.org/2/library/collections.html#collections.OrderedDict – ashwinjv Sep 03 '15 at 21:17
  • The essence of this question has been asked innumerable times on Stack Overflow. If you want a technical explanation for *why* Python dictionaries are unordered, [this](http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary) has some good answers. – John Y Sep 03 '15 at 21:26

2 Answers2

4

Dicts are not ordered. You may want to use OrderedDict: https://pymotw.com/2/collections/ordereddict.html

hellpanderr
  • 5,581
  • 3
  • 33
  • 43
1

In Python dictionary contains hashable objects as keys, you cannot except the order for it. If you try the below code you can see that.

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

You can use OrderedDict in collections, like below..

>>> from collections import OrderedDict
>>> d1 = OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>> d1
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>> for i in d1:
...     print i, d1[i]
... 
a 1
c 3
b 2
gsb-eng
  • 1,211
  • 1
  • 9
  • 16
  • Sorry I'm kind of new to dictionaries and thought I had a logical error. Thanks for responding regardless everyone! – user3163789 Sep 04 '15 at 02:07