0

The dictionary is supposed to have the 'N' key before 'D' but right now when it runs through the 'D' key is first, why is the append function adding D to the front instead of the ending of the dictionary?

Binary.txt is:

N = N D
N = D
D = 0
D = 1

the python file is

import sys
import string
from collections import defaultdict

#default length of 3
stringLength = 3

#get last argument of command line(file)
if len(sys.argv) == 1:
    #get a length from user
    try:
        stringLength = int(input('Length? '))
        filename = input('Filename: ')
    except ValueError:
        print("Not a number")

elif len(sys.argv) == 2:
    #get a length from user
    try:
        stringLength = int(input('Length? '))
        filename = sys.argv[1]
    except ValueError:
        print("Not a number")

elif len(sys.argv) == 3:
    filename = sys.argv[2]
    stringLength  = sys.argv[1].split('l')[1]
else:
    print("Invalid input!")





#checks

print(stringLength)
print(filename)

def str2dict(filename):
    result = defaultdict(list)
    with open(filename, "r") as grammar:
        #read file 
        lines = grammar.readlines()
        count = 0
        #loop through
        for line in lines:
            #append info 
            line = line.rstrip('\n')

            result[line[0]].append(line.split('=')[1])
            print(result)
    return result
FullCombatBeard
  • 323
  • 1
  • 11
  • 1
    dictionaries in python are unordered. use [OrederedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict). – Marcin Feb 04 '15 at 06:33
  • dictionaries in python are unordered. use [OrederedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict). – Marcin Feb 04 '15 at 06:35
  • Also see: http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python – Amir Rachum Feb 04 '15 at 06:37

2 Answers2

1

Standard dict is unordered. You should use collections.OrderedDict instead.

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17
0

From Python Docs:

It is best to think of a dictionary as an unordered set of key: value pairs[...]

(emphasis mine).

Amadan
  • 191,408
  • 23
  • 240
  • 301