python - Reading from file into dictionaries, and strange eval() behaviour -


creating dictionaries file using eval(), or ast.literal_eval() (as suggested others) yields strange results, , i'm not sure why.

my file, file.txt contains this:

{0 : {1: 6, 1:8}, 1 : {1:11}, 2 : {3: 9}, 3 : {},4 : {5:3},5 : {2: 7, 3:4}} 

i read dictionary , print contents out such

graph1 = {} graph1 = ast.literal_eval(open("file.txt").read()) 

and thing, {1:6} missing.

{0: {1: 8}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} 

i change contents of 'file.txt' this:

{0: {2: 7, 3: 4}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} 

and correct contents display!

then change contents of file.txt this, rewrite 1:6 2:6

{0 : {2: 6, 1:8}, 1 : {1:11}, 2 : {3: 9}, 3 : {},4 : {5:3},5 : {2: 7, 3:4}} 

and output, {2:6} , {1:8} switch places!

{0: {1: 8, 2: 6}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} 

all want correctly read contents of file dictionary. going wrong?

dictionaries can not have duplicate key. in case same key provided dict object, former value overridden later value.

for example:

>>> d = {'a': 'x', 'b': 'y', 'c': 'z', 'a': 'w'} >>> d {'a': 'w', 'c': 'z', 'b': 'y'}  # ('a': 'x') overridden ('a': 'w')  

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -