Python CSV: One code but unfortunately two diffrent results -
i have problems following code. i'm trying read datas csv file create nested dictonary. when run first time intent when run twice changes order of output. have idea why hapening? i'm using python 3.4.
import csv delimiter = ';' result = {} open("f:\\python projects\\database.csv", 'r') data_file: data = csv.reader(data_file, delimiter=delimiter) headers = next(data)[1:] row in data: temp_dict = {} name = row[0] values = [] x in row[1:]: values.append(x) in range(len(values)): temp_dict[headers[i]] = values[i] result[name] = temp_dict print(result)
my input looks this:
and result this:
column 1 shows diffrent order when run code twice.
from the docs have helpful note:
cpython implementation detail: keys , values listed in arbitrary order non-random, varies across python implementations, , depends on dictionary’s history of insertions , deletions.
it turns out there clever form of attack possible on web applications if can predict order dictionary keys stored. defeating clever attack involves changing way hashing works, using random "seed" every hash. makes dictionary ordering unpredictable, solves clever attack problem. means can't dump contents of dictionary , same results in same order each time.
you can ordered result in 1 of 2 ways. first, use collections.ordereddict
, or (probably better solution) make separate ordering phase, apply whatever logic want.
normally, separate ordering phase like:
for k,v in sorted(d.items()): print("\t{}: {}".format(k,v))
Comments
Post a Comment