0

I have txt file with two columns:

user1 1
user2 2
user3 3
user4 4
user5 5

So, I read columns to dictionary:

def read_users(filename):
    users = {}
    with open('1.txt', 'r') as f:
        for line in f:
            words = line.split()
            users[words[0]] = words[1]
    return users

Function returns the following dictionary:

{'user4':'4'}; {'user5':'5'}; {'user1':'1'}; {'user2':'2'}; {'user3':'3'}

Why does it begin with user4? It should be from user1 to user5. Order of strings in file is correct.

Alex Smith
  • 85
  • 2
  • 9

1 Answers1

0

Dictionaries are unordered. Technically, the order is

  • consistent (iterating over a dictionary will always produce results in the same order as long as you don't insert or delete any keys)
  • "arbitrary". There's no telling what order the items will be yielded.

It depends on the order in which the items are inserted and what the hash values of the keys are. If you're using python2.7, you can use a collections.OrderedDict which remembers insertion order. If you're really interested, see this answer about how Cpython determines the order of your mapping.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Thank you. Due to your advice I decided to use `collections.OrderedDict`. I've changed only 2 strings: `from collections import OrderedDict` and `users = OrderedDict()` - it works as I need. – Alex Smith May 20 '13 at 18:01