I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
theFile = open('word-happiness.csv', 'r')
theFile.close()
def make_happiness_table(filename):
''' make_happiness_table: string -> dict
creates a dictionary of happiness scores from the given file '''
return {}
make_happiness_table("word-happiness.csv")
table = make_happiness_table("word-happiness.csv")
(score, stddev) = table['hunger']
print("the score for 'hunger' is %f" % score)
I have the word 'hunger' in my file but when I run this program to take 'hunger' and return its given score and std deviation, I get:
(score, stddev) = table['hunger']
KeyError: 'hunger'
How is it that I get a key error even though 'hunger' is in the dictionary?
"hunger" isn't in the dictionary (that's what the KeyError tells you). The problem is probably your make_happiness_table function. I don't know if you've posted the full code or not, but it doesn't really matter. At the end of the function, you return an empty dictionary ({}) regardless of what else went on inside the function.
You probably want to open your file inside that function, create the dictionary and return it. For example, if your csv file is just 2 columns (separated by a comma), you could do:
def make_happiness_table(filename):
with open(filename) as f:
d = dict( line.split(',') for line in f )
#Alternative if you find it more easy to understand
#d = {}
#for line in f:
# key,value = line.split(',')
# d[key] = value
return d
Related
I am doing a small programming project for school, one of the main elements of my program is to be able to allow the user to enter a problem (e.g. "my phone screen is blank") and for me to iterate through each word of the string and compare it to a dictionary, and the dictionary must be an external text file, I would like help on the dictionary aspect of this. I have tried a few other methods from different posts of stack overflow but they do not seem to work.
Some lines of my dictionary include:
battery Have you tried charging your phone? You may need to replace your battery.
sound Your volume may be on 0 or your speakers may be broken, try using earphones.
blank Your screen may be dead, you may need a replacement.
Here, "battery,"sound" and "blank" are they keys with their respective values following on after, how do I plan on doing this?
Thank you!
[edited code]
def answerInput():
print("Hello, how may I help you with your mobile device")
a = input("Please enter your query below\n")
return a
def solution(answer):
string = answer
my_dict = {}
with open("Dictionary.txt") as f:
for line in f:
key, value = line.strip("\n").split(maxsplit=1)
my_dict[key] = value
for word in string.split():
if word == my_dict[key]:
print(value)
process = 0
answer = answerInput()
solution(answer)
my_dict = {} # defining it as a dictionary
with open("file.txt") as f: # opening txt file
for line in f:
key, value= line.strip("\n").split(maxsplit=1) # key is before first whitespace, value is after whitespace
my_dict[key] = value
This will work well, something I have used personally.
It initiates a dictionary called my_dict,
opens the file and for each line it strips \n from the line and splits it once only. This creates two values which we call key and value which we add to the dictionary in the form {key: value}
Or, using dict comprehension
with open("file.txt") as f: # opening txt file
my_dict = {k: v for k,v in (line.strip("\n").split(maxsplit=1) for line in f)}
I'm building a Twitter bot and I use a random query term. I save the date and query term to a text file. I would like to check if the current query term is in the last 5 values of my memory dictionary.
I read the .txt file, split into key and values of a dictionary and I'm not sure what to do next. In psuedo code, I'd like to say query = d.values(last value in dictionary : or in the last 5 values) and then I'd pick a new query.
2019-09-23,computerscience
2019-09-24,python
2019-09-25,computerprogrammer
2019-09-26,computerscience
2019-09-27,AI
2019-09-28,machinelearning
2019-09-29,neuralnetworks
2019-09-30,computerscience
d = {}
with open(file_name) as f:
for line in f:
(key, val) = line.split(",")
val = val[:-1]
d[key] = val
If I print(d.values()) it gives me all the values like I want which is great. Now I want to check what the last 5 values are. I'm using python 3.7 so the dictionary should be an ordered dict by default.
last_five = list(d.values())[-5:]
def check_query(queryterm):
if queryterm in last_five:
return True
else:
return False
I am not sure if I understood your question correctly, but from your last sentence, I infer you may want something like this:
d = {}
with open(file_name) as f:
for line in f:
(key, val) = line.split(",")
val = val[:-1]
d[key] = val
print(list(d.values())[-5:])
I have a file in the below format
.aaa b/b
.ddd e/e
.fff h/h
.lop m/n
I'm trying to read this file. My desired output is if I find ".aaa" I should get b/b, if I find ".ddd" I should get e/e and so on.
I know how to fetch 1st column and 2nd column but I don't know how to compare them and fetch the value. This is what I've written.
file = open('some_file.txt')
for line in file:
fields = line.strip().split()
print (fields[0]) #This will give 1st column
print (fields[1]) # This will give 2nd column
This is not the right way of doing things. What approach follow?
Any time you want to do lookups, a dictionary is going to be your friend.
You could write a function to load the data into a dictionary:
def load_data(filename):
result = dict()
with open(filename, 'r') as f:
for line in f:
k,v = line.strip().split() # will fail if not exactly 2 fields
result[k] = v
return result
And then use it to perform your lookups like this:
data = load_data('foo.txt')
print data['.aaa']
It sounds like what you may want is to build a dictionary mapping column 1 to column 2. You could try:
file = open('some_file.txt')
field_dict = {}
for line in file:
fields = line.strip().split()
field_dict[fields[0]] = fields[1]
Then in your other code, when you see '.ddd' you can simply get the reference from the dictionary (e.g. field_dict['.ddd'] should return 'e/e')
Just do splitting on each line according to the spaces and check whether the first item matches the word you gave. If so then do printing the second item from the list.
word = input("Enter the word to search : ")
with open(file) as f:
for line in f:
m = line.strip().split()
if m[0] == word:
print m[1]
How would I go about creating a python program to store a range of values (ie. apples=3, bananas=5, carrots=12.5) in an external file where I can later use those values for calculations later on?
Currently, I am able to print to and read from text files using fileinput and fileoutput, but I am unable to use those values in calculations later on.
with open("values.txt","w") as fileinput:
fileinput.write(value)
An example of what I am looking for is first being able to type a variable name (eg. Apples), then type a number or other value (eg. 3.3) and then print those values to the values.txt. That way, a separate program could view values.txt to be able to use the value of apples=3.3 in a calculation (eg. apples*3=9.9)
Assuming that you want to store fruit and values pairs into a dictionary (but you can adapt it to any data structure):
Writing to file:
fruits = {"apple":12, "banana":4}
with open("test.txt", 'w') as out:
for fruit,number in fruits.iteritems():
line = fruit + '=' + str(number) + '\n'
out.write(line)
Parse from file into dictionary
emptyDict = {}
with open("test.txt", 'r') as infile:
for line in infile:
tokens = line.strip().split('=')
fruit = tokens[0]
number = tokens[1]
emptyDict[fruit] = float(number)
What do you mean by "but I am unable to use those values in calculations later on.". But you could create a dictionary mapping the String to the values, for example:
mydata = {}
with open("values.txt", "r") as output:
for line in output:
tmp = line.split('=')
mydata[tmp[0]] = float(tmp[1])
I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
theFile = open('word-happiness.csv' , 'r')
theFile.close()
def make_happiness_table(filename):
'''make_happiness_table: string -> dict
creates a dictionary of happiness scores from the given file'''
with open(filename) as f:
d = dict( line.split(' ') for line in f)
return d
make_happiness_table("word-happiness.csv")
table = make_happiness_table("word-happiness.csv")
(score, stddev) = table['hunger']
print("the score for 'hunger' is %f" % score)
My .csv file is in the form
word{TAB}score{TAB}standard_deviation
and I am trying to create the dictionary in that way. How can I create such a dictionary so that I can print a word such as 'hunger' from the function and get its score and std deviation?
def make_happiness_table(filename):
with open(filename) as f:
d = dict()
for line in f:
word,score,std = line.split() #splits on any consecutive runs of whitspace
d[word]=score,std # May want to make floats: `d[word] = float(score),float(std)`
return d
Note that if your word can have a tab character in it, but you're guaranteed that you only have 3 fields (word, score, std), you can split the string from the right (str.rsplit), only splitting twice (resulting in 3 fields at the end). e.g. word,score,std = line.rsplit(None,2).
As mentioned in the comments above, you can also use the csv module to read these sorts of files -- csv really shines if your fields can be "quoted". e.g.:
"this is field 0" "this is field 1" "this is field 2"
If you don't have that scenario, then I find that str.split works just fine.
Also, unrelated, but your code calls make_happiness_table twice (the first time you don't assign the return value to anything). The first call is useless (all it does is read the file and build a dictionary which you can never use). Finally, opening and closeing theFile at the beginning of your script is also just a waste since you don't do anything with the file there.
If you are sure your word will not have space, you can just split the line e.g.
word, score, stddev = line.split()
But if word can have space use tab char \t to split e.g.
word, score, stddev = line.split('\t')
But for a very generic case when word may have tab itself use the csv module
reader = csv.reader(filename, dialect='excel-tab')
for word, score, stddev in reader:
...
and then you can create dict of word and score, stddev e.g.
word_dict[word] = (score, stddev)