简体   繁体   中英

Data Format Conversion Python

I have data in the following format;

(('option1', 'option1'),
('option2', 'option2'),
('option3', 'option3'))

And require it to be organized like this;

[{
    "option1": "option1"
}, {
    "option2": "option2"
}, {
    "option3": "option3"
}]

How would I go about this is python? It's to use in some data recieved by JQuery.

You can use a list comprehension:

[dict([opt]) for opt in inputlist]

Demo:

>>> inputlist = (('option1', 'option1'), ('option2', 'option2'), ('option3', 'option3'))
>>> [dict([opt]) for opt in inputlist]
[{'option1': 'option1'}, {'option2': 'option2'}, {'option3': 'option3'}]

If all your option keys are unique , however, you'd be far better of creating just one dictionary from these tuples:

>>> dict(inputlist)
{'option2': 'option2', 'option3': 'option3', 'option1': 'option1'}

Even if the keys are not unique, it'll much easier to map keys to lists or sets of associated values when you use one top-level dictionary:

result = {}
for key, val in inputlist:
    result.setdefault(key, []).append(val)

produces a result dictionary where each key references a list of values. If any keys appear more than once in the input list, the associated values are then accumulated. If order doesn't matter you could also use a set() (using result.setdefault(key, set()).add(val) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM