moomin
moomin

Reputation: 49

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

Creating dictionaries from file using eval(), or ast.literal_eval() (as suggested by others) yields strange results, and 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 it into a dictionary and print the contents out as such

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

and I get this thing, where the {1:6} is missing.

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

I change the contents of 'file.txt' to this:

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

And then the correct contents display!

Then I change the contents of file.txt to this, where I rewrite 1:6 as 2:6

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

And this is the output, where {2:6} and {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 I want to do is correctly read the contents of a file into my dictionary. What is going wrong?

Upvotes: 1

Views: 57

Answers (2)

Kasravnd
Kasravnd

Reputation: 107297

The reason of missing 1:6 is because of that you have 1:8 in your dictionary too, and since python use hash table for implementing the dictionaries, they don't preserve duplicate keys (because they have same hash value) and the reason of changing the order is that dictionaries don't have a specific order because of the way they are implemented.

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

Dictionaries can not have duplicate key. In case same key is provided to the dict object, former value is overridden by the later value.

For example:

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

Upvotes: 1

Related Questions