Dinosaurius
Dinosaurius

Reputation: 8638

How to solve TypeError: 'int' object has no attribute '__getitem__'?

I have written the following code, but it fails with the error message TypeError: 'int' object has no attribute '__getitem__' at line if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):. The object json_string is obtained with json_string = json.loads(text)

def getField(dt,json_string):

    fields = {k['type']: ((k['start-month'],k['start-day']),(k['end-month'],k['end-day'])) for k in json_string}

    field = "NA"    
    for t, ranges in fields.items():
        for start, end in ranges:
            if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):
                field = t
                break
        if field != "NA":
            break
    return field 

text = '''[{"end-day":31,"end-month":5,"type":"T1","start-day":10,"start-month":1},{"end-day":9,"end-month":1,"type":"T2","start-day":1,"start-month":9},{"end-day":30,"end-month":9,"type":"T3","start-day":1,"start-month":6}]'''

json_string = json.loads(text)
dt = datetime.strptime("2015-03-12 11:00:00.0", "%Y-%m-%d %H:%M:%S.%f")

getField(dt,json_string)

UPDATE:

The content of fields:

{u'Type1': ((6, 1), (9, 30)),
 u'Type2': ((1, 10), (5, 31)),
 u'Type3': ((9, 1), (1, 9))}

Upvotes: 0

Views: 4780

Answers (2)

BoarGules
BoarGules

Reputation: 16951

From this:

if date(dt.year,start[0],start[1]) 

it is clear that you are expecting start to be a tuple containing month and day. But if I do this:

for t, ranges in fields.items():
    for start, end in ranges:
        print (f"start={start} end={end}")

I get:

start=6 end=1
start=9 end=30
start=1 end=10
start=5 end=31
start=9 end=1
start=1 end=9

Now you can see where the error message is coming from. start[0] means 6[0]. Do this instead:

for t, (start,end) in fields.items():

Then start and end will be the month/day tuples you expect.

Upvotes: 2

lxop
lxop

Reputation: 8615

What you ought to be doing is

start, end = ranges

rather than looping through them. Also, ranges isn't a good name, something like date_pairs might make more sense.

What you have in ranges is a sequence of pairs (2 of them, to be exact). Thus the for loop will iterate twice - once for the pair of ints representing the start date, and once for the pair of ints representing the end date. In each iteration, start and end will be integers, not pairs, so you can't index them.

Upvotes: 1

Related Questions