0

I have problems with the following Code. I'm trying to read datas from a CSV file to create a nested dictonary. When I run it the first time it does exactly what I intent but when I run it twice it changes the order of the output. Does anyone have an idea why this is hapening? I'm using Python 3.4.

import csv

delimiter = ';'
result = {}

with open("F:\\Python Projects\\Database.csv", 'r') as data_file:
data = csv.reader(data_file, delimiter=delimiter)
headers = next(data)[1:]
for row in data:
    temp_dict = {}
    name = row[0]
    values = []
    for x in row[1:]:
        values.append(x)
    for i in range(len(values)):
        temp_dict[headers[i]] = values[i]
    result[name] = temp_dict    
print(result)

My input looks like this:

Input_CSV

and the result is this:

Output

Column 1 shows a diffrent order when I run the code twice.

Max2603
  • 403
  • 1
  • 6
  • 23
  • 2
    Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering. See http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key – John Karasinski May 28 '16 at 19:09
  • You can use an `OrderedDict` as suggested in the answer linked by @karasinski. – leekaiinthesky May 28 '16 at 19:34
  • I don't mean to order the row but the column. In my Opinion it should have the order like my csv file cause the code is running trough it from the beginning to the end, or am I wrong? – Max2603 May 28 '16 at 19:42

1 Answers1

0

From the docs we have this helpful note:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

It turns out that there is a clever form of attack that is possible on web applications if you can predict the order that dictionary keys will be stored. Defeating this clever attack involves simply changing the way hashing works, by using a random "seed" with every hash. This makes dictionary ordering unpredictable, which solves the clever attack problem. But it means you can't dump the contents of a dictionary and get the same results in the same order each time.

You can get an ordered result in one of two ways. First, you could use a collections.OrderedDict, or (probably a better solution) you could make a separate ordering phase, where you apply whatever logic you want.

Normally, the separate ordering phase will look something like:

for k,v in sorted(d.items()):
    print("\t{}: {}".format(k,v))
aghast
  • 14,785
  • 3
  • 24
  • 56