Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda