Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
how to convert a text to dict in order to iterate it in python?

What i am trying to do is to iterate. I have this line of code in one column in a table in my database:

[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]

i assign this to a variable order so i have:

order = [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]

then i want to iterate it. I am trying the follow:

   for o in order.items():
        product = o['item']
        ...

it doesn't work. How can i convert it?

    for order in orders:
        ord = order.shopping_cart_details # [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]
        temp = {'order_id': order.id, 'movies': ord['item'], 'created': order.created}
        full_results.append(temp)

i get string indices must be integers

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Could you check the return data type after you retrieve the data from database for the following code:

[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]

Use type(order) to determine the type of the return value. It might be that the return data for the above data is in string format. In this case, when you store the list into database, you may consider to use json.dumps() to convert the data first then later when you retrieve the data, you may use json.loads() to get back the original data type. In this case, you may consider to change the database column type to blob.

over 4 years ago · Santiago Trujillo Report

0

Assume the order is a string

order = '[{"item": 5, "quantity": 2},{"item": 6, "quantity": 1}]'

def doSomething():
    import json
    ord = json.loads(order) 
    values =[ v['item'] for v in ord] # if u want a single item u put values = v.pop()['item']
over 4 years ago · Santiago Trujillo Report

0

Or to make it more simple you can use eval function.

order = '[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]'
order = eval(order)
for o in order:
    product = o['item']
    print product
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!