FullCombatBeard
FullCombatBeard

Reputation: 313

Python dictionary appending is adding to front of dictionary instead of end

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

Upvotes: 0

Views: 1399

Answers (2)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

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.

Upvotes: 1

Amadan
Amadan

Reputation: 198324

From Python Docs:

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

(emphasis mine).

Upvotes: 0

Related Questions