0
last_two_programs_dict = {} 

auto_cur.execute(
    "SELECT service_key, event_id, start_date_time, duration, prog_name "
    "FROM autodb.ssr_events "
    "WHERE (ca_details='FTA' OR ca_details='SUB') "  
    "AND recordable_event='1' "
    "AND start_date_time > CURRENT_TIMESTAMP() + 180 "
    "AND start_date_time <=> start_date_time "
    "AND duration > '00:04:00' "
    "AND service_key != '4061' "
    "ORDER BY start_date_time ASC "
    "LIMIT 2 "
)

last_two_programs = auto_cur.fetchall()

for program in last_two_programs:

    last_two_programs_dict['service_key'] = event[0]
    last_two_programs_dict['event_id'] = event[1]
    last_two_programs_dict['start_date_time'] = event[2].strftime("%Y%m%dT%H%M%SZ")
    last_two_programs_dict['duration'] = '0'+str(event[3])
    last_two_programs_dict['program_name'] = event[4]


print "Last Two programs dict", last_two_programs_dict

I would like to get the last two programs. When I run this query, it gives me only one. How can I get the last two records ?

1
  • 1
    Can't you iterate the cursor with "for program in auto_cur: " ? Also, does your sql query actually return two rows? Commented Feb 20, 2017 at 11:55

2 Answers 2

2

You should try this:

last_two_programs = [
    {
        'service_key': event[0]
        'program_id': event[1]
        'start_date_time': event[2].strftime("%Y%m%dT%H%M%SZ")
        'duration': '0' + str(event[3])
        'program_name': event[4]
    } for event in auto_cur.fetchall()
]

It's called list comprehension

Sign up to request clarification or add additional context in comments.

Comments

0

You are overwriting the dict in your loop, create a list and append the dicts to it on every iteration.

last_two_programs_list = []
for program in last_two_programs:
    # create a new dict every iteration
    last_two_programs_dict = {} 

    last_two_programs_dict['service_key'] = event[0]
    last_two_programs_dict['event_id'] = event[1]
    last_two_programs_dict['start_date_time'] = event[2].strftime("%Y%m%dT%H%M%SZ")
    last_two_programs_dict['duration'] = '0'+str(event[3])
    last_two_programs_dict['program_name'] = event[4]

    # append the dict to the list
    last_two_programs_list.append(last_two_programs_dict)

Also, you iterate the cursor directly rather than storing the resultset in a list.

last_two_programs_list = []
for program in auto_cur:
   # create a new dict every iteration
   last_two_programs_dict = {} 
   ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.