Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list of dictionaries

I have a simple code to fetch users from db using sqlalchemy and return them as json. My problem is how to format the output to get something like this:

{"results": [{"id":1, "username":"john"},{"id":2,"username":"doe"}]}

my code outputs an error which I cant seem to fix being a newbie in python:

d = []

for user in Users.query.all():
    v = {}
    for columnName in Users.__table__.columns.keys():
        v[columnName] = getattr( user, columnName )

    d.append( v )

return jsonify( d )

The code says:

ValueError: dictionary update sequence element #0 has length 11; 2 is required

Thanks.

like image 674
Rob P. Avatar asked May 30 '11 19:05

Rob P.


People also ask

Can you have a list of dictionaries in Python?

In Python, we can have a list or an array of dictionaries. In such an object, every element of a list is a dictionary. Every dictionary can be accessed using its index.

What is list of dictionary in Python?

Lists are mutable data types in Python. Lists is a 0 based index datatype meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. Lists are one of the 4 data types present in Python i.e. Lists, Dictionary, Tuple & Set.


2 Answers

I solved this error by simply saying

return jsonify( results = d )

instead of

return jsonify( d )
like image 110
Croo Avatar answered Oct 12 '22 14:10

Croo


Ah, now that your code has been pasted, I can see that the fundamental problem is indeed coming from jsonify. The below workaround should be satisfactory.

>>> import json
>>> json.dumps({"results": [{"id":1, "username":"john"},{"id":2,"username":"doe"}]})
'{"results": [{"username": "john", "id": 1}, {"username": "doe", "id": 2}]}'

Replace jsonify with json.dumps, and let me know if that doesn't fix the problem.

But if you'd prefer to use flask.jsonify, then you should take a look at the flask documentation. The argument to jsonify should be the same as the argument to any dict constructor -- i.e. a dict or an iterable of tuples. So that's the problem.

like image 21
senderle Avatar answered Oct 12 '22 15:10

senderle