FullCombatBeard
FullCombatBeard

Reputation: 313

Dictionaries overwriting in Python

This program is to take the grammar rules found in Binary.text and store them into a dictionary, where the rules are:

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

but the current code returns D: D = 1, N:N = D, whereas I want N: N D, N: D, D:0, D:1

import sys
import string

#default length of 3
stringLength = 3

#get last argument of command line(file)
filename1 = sys.argv[-1]


#get a length from user
try:
    stringLength = int(input('Length? '))
    filename = input('Filename: ')
except ValueError:
    print("Not a number")

#checks
print(stringLength)
print(filename)

def str2dict(filename="Binary.txt"):
    result = {}
    with open(filename, "r") as grammar:
        #read file 
        lines = grammar.readlines()
        count = 0
        #loop through
        for line in lines:
            print(line)
            result[line[0]] = line
            print (result)
    return result

print (str2dict("Binary.txt"))

Upvotes: 0

Views: 70

Answers (2)

UltraInstinct
UltraInstinct

Reputation: 44444

Firstly, your data structure of choice is wrong. Dictionary in python is a simple key-to-value mapping. What you'd like is a map from a key to multiple values. For that you'll need:

from collections import defaultdict
result = defaultdict(list)

Next, where are you splitting on '=' ? You'll need to do that in order to get the proper key/value you are looking for? You'll need

key, value = line.split('=', 1) #Returns an array, and gets unpacked into 2 variables

Putting the above two together, you'd go about in the following way:

result = defaultdict(list)
with open(filename, "r") as grammar:
    #read file 
    lines = grammar.readlines()
    count = 0
    #loop through
    for line in lines:
        print(line)
        key, value = line.split('=', 1)
        result[key.strip()].append(value.strip())
return result

Upvotes: 2

aruisdante
aruisdante

Reputation: 9075

Dictionaries, by definition, cannot have duplicate keys. Therefor there can only ever be a single 'D' key. You could, however, store a list of values at that key if you'd like. Ex:

from collections import defaultdict

# rest of your code...

result = defaultdict(list) # Use defaultdict so that an insert to an empty key creates a new list automatically
with open(filename, "r") as grammar:
    #read file 
    lines = grammar.readlines()
    count = 0
    #loop through
    for line in lines:
        print(line)
        result[line[0]].append(line)
        print (result)
return result

This will result in something like:

{"D" : ["D = N D", "D = 0", "D = 1"], "N" : ["N = D"]}

Upvotes: 1

Related Questions