more pythonic way to format a JSON string from a list of tuples
There is a much better way to generate JSON strings: the json
module.
import json
rs = json.dumps(dict(lst))
This takes advantage of the fact that dict()
can take a sequence of key-value pairs (two-value tuples) and turn that into a mapping, which the json
module directly translates to a JSON object structure.
Demonstration:
>>> import json
>>> lst = [("name", "value"), ("name2", "value2")]
>>> rs = json.dumps(dict(lst))
>>> print rs
{"name2": "value2", "name": "value"}
(lambda lst: json.dumps({item[0]:item[1] for item in lst}))([(1,2), (3,4)])