Python Dictionary Type - list

I'm trying to figure out why I get this type error. Is it possible to put integers inside of dictionaries?
math_questions = [
{'question1':'1*1',
'answer1':1,
'quote1' :'What you are,you are by accident of birth; what I am,I am by myself.\n There are and will be a thousand princes; there is only one Beethoven.'},
{'question2':'2*1',
'answer2':2,
'quote2': 'Two is company, three is a crowd'},
{'question3': '3*1',
'answer3': 3,
'quote3': 'There are three types of people, those who can count and those who cannot'}
]
# read from a txt file later???
print math_questions[0]['question1']
math_answer = int(raw_input("What is the answer to " + math_questions["question1"] +"? : "))
if math_answer == math_questions['answer1']:
print math_questions['quote']
else:
print "Try again"
print math_questions['answer1']
This is the error message I get.
PS C:\python27\math_game> python math_game.py
1*1
Traceback (most recent call last):
File "math_game.py", line 17, in <module>
math_answer = int(raw_input("What is the answer to " + math_questions["question1"] +"? : "))
TypeError: list indices must be integers, not str
PS C:\python27\math_game>
Thanks for the help in advance.

When you access a list, you need the index. It looks like you are trying to access a dict. Instead, put:
math_answer = int(raw_input("What is the answer to " + math_questions[0]["question1"] +"? : "))
You had a few errors:
You had math_questions["question1"] on line 17, 19, 20, 23
You had math_questions["quote"] which didn't exist (I changed to math_questions["quote1"])
Over here, we try to access a list of dicts by the way you used. However, we need to strip it to just the dict before we access it that way.
>>> obj = [{'data1': 68,
... 'data2': 34,
... 'data3': 79}]
>>> obj['data2']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> obj[0]['data2']
34
>>>
Here is your updated code:
math_questions = [
{'question1':'1*1',
'answer1':1,
'quote1' :'What you are,you are by accident of birth; what I am,I am by myself.\n There are and will be a thousand princes; there is only one Beethoven.'},
{'question2':'2*1',
'answer2':2,
'quote2': 'Two is company, three is a crowd'},
{'question3': '3*1',
'answer3': 3,
'quote3': 'There are three types of people, those who can count and those who cannot'}
]
# read from a txt file later???
print math_questions[0]['question1']
math_answer = int(raw_input("What is the answer to " + math_questions[0]["question1"] +"? : "))
if math_answer == math_questions[0]['answer1']:
print math_questions[0]['quote1']
else:
print "Try again"
print math_questions[0]['answer1']

You should rework your data structure similar to this:
class MathQuestion:
def __init__(self, question, answer, quote):
self.question = question
self.answer = answer
self.quote = quote
math_questions = [
MathQuestion(question='1*1', answer='1', quote='What you are …'),
MathQuestion(question='2*1', answer='2', quote='Two is company …'),
#…
]
This allows you to address your strings like this:
math_questions[0].answer

Related

adding item in the dictionary coming from a list resulted in TypeError

this is the code:
import bisect
data = {'sal': 25000} # stored data from user input
table = {1249.99: 36.30, 1749.99: 54.50, 2249.99: 72.70, 2749.99: 90.80,
3249.99: 109.00, 3749.99: 127.20, 4249.99: 145.30, 4749.99: 163.50,
5249.99: 181.70, 5749.99: 199.80, 6249.99: 218.00, 6749.99: 236.20,
7249.99: 254.30, 7749.99: 272.50, 8249.99: 290.70, 8749.99: 308.80,
9249.99: 327.00, 9749.99: 345.20, 10249.99: 363.30, 10749.99: 381.50,
11249.99: 399.70, 11749.99: 417.80, 12249.99: 436.00, 12749.99:
454.20, 13249.99: 472.30, 13749.99: 490.50, 14249.99: 508.70,
14749.99: 526.80, 15249.99: 545.00, 15749.99: 563.20, 15750.00:
581.30}
# get corresponding value from the table
table_bisect = bisect.bisect(sorted(table), data['sal'])
if table_bisect >= 30:
table_bisect = 30
else:
table_bisect = table_bisect
s_table = sorted(table.value())
data['new'] = ''.join(s_table[table_bisect:(table_bisect+1)]
# TypeError: sequence item 0: expected string, float found
Everything works fine, until the last line, which return the error above. How can I fix the error or what are the work around?
It is because if you slice with list[index:index+1], it simply returns one value, which in this case is a float:
>>> y = [21, 4, 2, 5, 4, 3, 7, 9]
>>> y[5:6]
[3]
>>> ''.join(y[5:6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>>
Instead, just do the following:
data['new'] = s_table[table_bisect:(table_bisect+1)][0]
Another option is to do this:
data['new'] = ''.join(str(s_table[table_bisect:(table_bisect+1)]))
the join() method expects string type if you need to use it.

input of a tuple on the command line and assigning it to a tuple

I want to input pairs of coordinates (points) to define a line (vector) and want to do somthing like:
var = raw_input("Input LineA (x1,y1,x2,y2) ")
lineA[0][0]=var[0]
lineA[1][0]=var[1]
lineA[0][1]=var[2]
lineA[1][1]=var[3]
print lineA
lineA should be used as a tuple of tuples, á la:
lineA = ((2.5,2.0),(3.0,4.0))
Anyone any clue how to solve this elegantly? At present I'm getting
Traceback (most recent call last): File "win.py", line 34, in
<module>
lineA[0][0]=var[0] TypeError: 'tuple' object does not support item assignment
Try this:
lineA = ((var[0], var[2]), (var[1], var[3]))
Tuples are immutable so you can't assign values to its individual elements (as opposed to lists).
#Edit1:
Sorry I didn't pay attention to the 1st line. Here's an update:
raw_str = raw_input("Input LineA (x1,y1,x2,y2): ")
# Split the string by commas(this is the separator), raise Exception if we have more or less than 4 values.
tokens = raw_str.split(",")
if len(tokens) != 4:
raise ValueError("Invalid input.")
# Now we eliminate any SPACEs, TABs, or ; that the user might have input and then convert everything to floats.
var = [item.strip(" \t;") for item in tokens]
lineA = ((float(var[0]), float(var[2])), (float(var[1]), float(var[3])))

Parsing txt file using python : List index out of range

Hello I have written a python program to parse data specific data from txt file
my code is:
f = open('C:/Users/aikaterini/Desktop/Ericsson_PARSER/BSC_alarms_vf_OSS.txt','r')
from datetime import datetime
import MySQLdb
def firstl():
with f as lines:
lines = lines.readlines()
print len(lines)
for i,line in enumerate(lines):
if line.startswith("*** Disconnected from"):
conline = line.split()
bsc = conline[-2]
print "\n"*5
print bsc
print "*"*70
break
for i,line in enumerate(lines):
if line.startswith("*** Connected to"):
conline = line.split()
bsc = conline[-2]
print "\n"*5
print bsc
print "*"*70
elif line[:3] == "A1/" or line[:3] == "A2/":
if lines[i+1].startswith("RADIO"):
fal = line.split()
first_alarm_line = [fal[0][:2],fal[-2],fal[-1]]
year = first_alarm_line[1][:2]
month = first_alarm_line[1][2:4]
day = first_alarm_line[1][4:]
hours = first_alarm_line[2][:2]
minutes = first_alarm_line[2][2:]
date = datetime.strptime( day + " " + month + " " + year + " " + \
hours+":"+minutes,"%d %m %y %H:%M")
print first_alarm_line
print date, "\n"
print lines[i+1]
print lines[i+4]
print lines[i+5]
desc_line = lines[i+4]
desc_values_line = lines[i+5]
desc = desc_line.split(None,2)
print desc
desc_values = desc_values_line.split(None,2)
rsite = ""
#for x in desc_values[1]:
# if not (x.isalpha() or x == "0"):
# rsite += x
rsite = desc_values[1].lstrip('RBS0')
print "\t"*2 + "rsite:" + rsite
if desc[-1] == "ALARM SLOGAN\n":
alarm_slogan = desc_values[-1]
print alarm_slogan
x = i
print x # to check the line
print len(line) #check length of lines
while not lines[x].startswith("EXTERNAL"):
x+=1
if lines[x].startswith("EXTERNAL"):
while not lines[x] == "\n":
print lines[x]
x+=1
print "\n"*5
elif lines[i+1].startswith("CELL LOGICAL"):
fal = line.split()
first_alarm_line = [fal[0][:2],fal[-2],fal[-1]]
#print i
print first_alarm_line
type = lines[i+1]
print type
cell_line = lines[i+3]
cell = cell_line.split()[0]
print cell
print "\n"*5
##########Database query###########
#db = MySQLdb.connect(host,user,password,database)
firstl()
when i run the program the results are correct
but it prints until line 50672 while there are 51027
and i get the last printed result with the following error:
['A2', '130919', '0309']
2013-09-19 03:09:00
RADIO X-CEIVER ADMINISTRATION
MO RSITE ALARM SLOGAN
RXOCF-18 RBS03668 OML FAULT
['MO', 'RSITE', 'ALARM SLOGAN\n']
rsite:3668
OML FAULT
50672
51027
Traceback (most recent call last):
File "C:\Python27\parser_v3.py", line 106, in <module>
firstl()
File "C:\Python27\parser_v3.py", line 72, in firstl
while not lines[x].startswith("EXTERNAL"):
IndexError: list index out of range
if i comment the while not line i get :
Traceback (most recent call last):
File "C:\Python27\parser_v3.py", line 106, in <module>
firstl()
File "C:\Python27\parser_v3.py", line 60, in firstl
rsite = desc_values[1].lstrip('RBS0')
IndexError: list index out of range
The txt content is like :
A1/EXT "FS G11B/25/13/3" 382 150308 1431
RADIO X-CEIVER ADMINISTRATION
BTS EXTERNAL FAULT
MO RSITE CLASS
RXOCF-16 RBS02190 1
EXTERNAL ALARM
ALARM SYSTEM ON/OFF G2190 DRAMA CNR
A1/EXT "FS G11B/25/13/3" 755 150312 1434
RADIO X-CEIVER ADMINISTRATION
BTS EXTERNAL FAULT
MO RSITE CLASS
RXOCF-113 RBS00674 1
EXTERNAL ALARM
IS.BOAR FAIL G0674 FALAKRO
I don't understand since i do a split with maxnumber 2 and i get 3 elements as u can see and i am picking the 2nd and if i comment that i get another error when i pick an element from a list and the thing is that returning the correct result.Please help me.
Sorry for the long post thank you in advance.
I'm haven't dug deep into your code, but have you tried validating that x does not exceed the number of elements in lines before trying to access that index? Also, for readability I'd suggest using lines[x] != rather than not lines[x] ==
while x < len(lines) and lines[x] != "\n":
I solved it although i don't know if it is correct way but it works.
I think the problem was that the x was exceeding the length of the list lines containing the file and there had to be a check after the split that the list had length larger or equal to number of elements so :
if len(desc_values) > 2 and len(desc) > 2:
rsite = desc_values[1].lstrip('RBS0')
print "\t"*2 + "rsite:" + rsite
if desc[-1] == "ALARM SLOGAN\n":
alarm_slogan = desc_values[-1]
print alarm_slogan
x = i
print x #to check the line
print len(lines) # check length of lines
while [x] < len(lines): #check so that x doesnt exceed the length of file list "line"
while not lines[x].startswith("EXTERNAL"):
x+=1
if lines[x].startswith("EXTERNAL"):
while lines[x] != "\n":
print lines[x]
x+=1
Thank you man you really helped me although i am trying to find a way to stop the iteration of x to gain some computation time i tried break but it throws you completely of the loop.
Thanks anyway

Sequential Search: Input Length Isn't Detected Python

I'm writing a program where the user inputs a list of numbers, and then is asked which number he or she wants the program to return that numbers position. (Ex. 3,5,1,9,12,6 --> find position in list where 9 occurs)
I can get this to work if I hard code the list and the search number, but I'm having trouble with input. Mostly my problem is that Python isn't detecting the length of the list of numbers but I'm not sure how to fix this.
Here is the code I have:
def List(line):
list = []
for e in line.split(','):
list.append(int(e))
def Search(num, list):
for i in range(len(list)):
if list[i] == num:
return i
return -1
def main():
line = input("Enter list of numbers separated by commas: ")
p = input("Number searching for")
print(List(line))
a = Search(p, list)
print(a)
main()
And here's the error:
Traceback (most recent call last):
File "G:\Final Exam Practice\linearsearch.py", line 24, in <module>
main()
File "G:\Final Exam Practice\linearsearch.py", line 19, in main
a = Search(p, list)
File "G:\Final Exam Practice\linearsearch.py", line 7, in Search
for i in range(len(list)):
TypeError: object of type 'type' has no len()
First, this answer has something you could use. list.index is a class method that returns the index of a list item:
>>> mylist = [3,5,1,9,12,6]
>>> mylist.index(9)
3
Next, a TypeError is raised because list is one of Python's reserved keywords. If you want to pass a list to your Search function, don't name it 'list'.
Just changing the name of the 'list' variable in the function will solve your problem. Additionally, here's another way to define search (Python function names are usually lowercase):
def search(num, mylist):
try:
return mylist.index(num)
except:
return -1

Python 2.7.3 Mergesort Receiving -- "TypeError: object of type 'file' has no len()"

I am just about done writing my first mergesort program and am running into trouble when compiling. I have done a bunch of research on this particular error and it seems I'm being non-specific somewhere in my code. I still cannot find said error and would love your help. I have attached the file contents, code, and traceback. Thanks again.
File:
999 Message C1
1033 Message C2
1054 Message C3
1056 Message C4
1086 Message C5
Code:
DEBUG = True
out = []
logs = open("C:\Users\----\Desktop\logs.txt", mode ="r")
lines = logs.readline()
def debug(s):
if DEBUG:
print "DEBUG: ", s
def get_t (line):
s = line
s = s.lstrip()
debug(s)
i = s.find(" ")
debug(s)
s = s[:i]
return int(s)
def get_lowest_i(logs):
lowest_i = -1
for i in range(len(logs)):
log = logs[i]
debug("log=" + repr(log))
if log:
t = get_t(log[0])
debug("t=" + repr(t))
if lowest_i == -1 or t < lowest_t:
lowest_i = i
lowest_t = t
return lowest_i
def get_line_lowest_t(logs):
while True:
i = get_lowest_i(logs)
if i == -1:
break
line = logs[i].pop(0)
def mergesort(logs):
while True:
line = get_line_lowest_t(logs)
if line == None:
break
out.append(line)
return out
print mergesort(logs)
f.close()
Traceback:
Traceback (most recent call last):
File "<module1>", line 50, in <module>
File "<module1>", line 44, in mergesort
File "<module1>", line 37, in get_line_lowest_t
File "<module1>", line 24, in get_lowest_i
TypeError: object of type 'file' has no len()
Thanks in advance.
TypeError: object of type 'file' has no len() the error says it all you are trying to read the length of a file object ... being that logs = open("C:\Users\----\Desktop\logs.txt", mode ="r") is a file maybe you mean to read the lines of the file and sort that ... lines = longs.readlines() print mergesort(lines)
file has no method len(). Put it into strings or arrays and then use len()
You are mergesorting the file, not the array called lines.