recurse through json in python - python

I have a sample json:
I want to use the json module of python and recurse through to find the "MaxSize" in "pevcwebasg". Have the following code:
import json
param_file_handle = json.load(open("sample.json"))
print param_file_handle['Resources']['pevcwebasg']['Type']
resources = param_file_handle['Resources']
for asg in resources:
print asg["Type"]
The out put of which is :
> AWS::AutoScaling::AutoScalingGroup Traceback (most recent call last):
> File "test.py", line 8, in <module>
> print asg['Type'] TypeError: string indices must be integers
What I dont get is this line "print param_file_handle['Resources']['pevcwebasg']['Type']" works fine and gets me the output but when i recurse through and try and find asg["Type"], it fails. Any better way to do this ? I need to recurse through the tree and find the value.
Edit 1:
as I do recurse through values, I get stuck with error.
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
for values in asg['Properties']:
print values["MaxSize"]
error :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print values["MaxSize"]
TypeError: string indices must be integers

for asg in resources:
This iterates through the keys of resources, rather than the values. Try:
for asg in resources.values():

param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
print asg["Properties"]["MaxSize"]
try this.

you broke hirerchy, missed "pevcwebasg"
resources = param_file_handle['Resources']['pevcwebasg']
for asg in resources:
print asg["Type"]

Related

IndexError: list index out of range with different functions

I am not quite sure what it is I am doing wrong with my code to get this error. I've been looking around to see if I could find somebody having the same problem but I have had no success thus far. The code is:
def sort(dislis):
for index in range(0,len(lst)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
The traceback error is:
Traceback (most recent call last):
File "C:", line 49, in <module>
distance()
File "", line 47, in distance
sort(dislis)
File "", line 20, in sort
currval= dislis[index]
IndexError: list index out of range
def sort(dislis):
for index in range(0,len(dislis)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
return dislis
result = sort([3,4,2,1])
print(result)
A few little bugs in there preventing it from running, try this out instead.
Also, I highly recommend using only spaces, and not tabs at all.

OverflowError: range() result has too many items, although it hasn't

I have this for-loop:
for i in range(1000000000, 1000000030):
foo(i)
When I execute it this error is given:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 11, in <module>
for i in range(1000000000, 10000000030):
OverflowError: range() result has too many items.
As far as I know, this range-object should have exactly 30 elements...
Where is the problem?
Edit:
I have removed the extra zero, now I get this:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 12, in <module>
factorizeInefficient(i)
MemoryError
Edit 2:
def factorizeInefficient(n):
teiler = list()
for i in range(n):
if i != 0:
if (n%i)==0:
teiler.append(i)
print teiler
Just found the solution myself: There is a range(n) object in this as well and this causes the memory Error...
An extra question: How did you guys know this was python 2? (Btw you were right...)
Copy/pasting the range() part of your code:
>>> len(range(1000000000, 10000000030))
9000000030
So there are actually about 9 billion elements in the range. Your first argument is presumably missing a zero, or second argument has a zero too many ;-)
count your zeros once again ;) I'd say it's one too much.

Getting error in Executing BLOSUM62 matix

I'm trying to extract data from blosum62 matrix
I have done the following code:
from Bio.SubsMat import MatrixInfo
blosum = MatrixInfo.blosum62
blosum['N','D']
et gets following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ('N', 'D')
But in blosum62 matrix there is a value of ('N','D') = 1
Why is it giving KeyError ?
I think Blosum62 is a lower triangular matrix so if ('N','D') is not working then go with ('D','N')
the solution is
pair = ('N','D')
if pair not in blosum62_matrix:
value = blosum62_matrix[(tuple(reversed(pair)))]
else:
value = blosum62_matrix[pair]
I think it will work.
Accroding to http://biopython.org/DIST/docs/api/Bio.SubsMat.MatrixInfo-module.html#blosum62 blosom62 returns a dictionary. So try blosum[('N','D')].

Traceback error in python

When I use the float() method in a program , I am getting an error. Can you please help me with that. I am using python 3.4.0a4.
This is the program:
import urllib.request
price = 99.99
while price > 4.74:
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
Print("Buy!")
and this is the error I get:
Traceback (most recent call last):
File "F:/Python/python 8.py", line 11, in <module>
price = float(text[start_of_price:end_of_price])
ValueError: could not convert string to float: '!DOC'
It seems like you sliced the string of the web page at the wrong position, and the result of text[start_of_price:end_of_price] is !DOC.
This is not a valid number and can hence not be converted to a float.
This is the exact code given in Head first Programming. The link was broken and I got the output on correcting it. Thanks for your help..

Return the average mark givin the respective lecture

Each line represents a single student and consists of a student number, a name, a section code and a midterm grade, all separated by whitespace.
The first parameter is already done and the file is open and
The second parameter is a section code
this is the link http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt
My code:
def average_by_section(the_file, section_code):
'''(io.TextIOWrapper, str) -> float
Return the average midtermmark for all students in that section
'''
score = 0
n = 0
for element in the_file:
line = element.split()
if section_code == line[-2]:
mark = mark + float(line[-1])
n += 1
lecture_avg = mark / n
return lecture_avg
I'm getting an index out of range. Is this correct? Or am I just opening up the wrong file?
can someone test this code and download that file? I'm pretty sure it should work, but not for me.
Well, you can troubleshoot the index out of range error with a print line or print(line) to explore the number of items in "line" (i.e. the effect of split()). I'd suggest looking closer at your split() statement...
It looks like you are omitting parts of your code where you define some of those variables (section_code, mark, etc.), but adjusting for some of those things seems to work properly. Assuming that the error you got was IndexError: list index out of range, that happens when you try to access an element of a list by index where that index doesn't exist. For instance:
>>> l = ['one']
>>> l[0]
'one'
>>> l[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[-1]
'one'
>>> l[-2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Therefore in your code, you will get that error if line is ever fewer than two items. I would check and see what you are actually getting for line to make sure it is what you expect.

Categories

Resources