I have a JSON like:
data = [
{"word": "Hi", "lang": "en"},
{"word": "Bonjour", "lang": "fr"},
...
]
I want to execute a function (named db.insertIntoSwearWords) for each key-value pair.
This is what I've done so far
words = [item['word'] for item in data]
langs = [item['lang'] for item in data]
res = [db.insertIntoSwearWords(words[i], langs[i]) for i in range(len(words))]
result = [{'word': words[i], 'result': res[i]} for i in range(len(words))]
print(jsonify(result))
which gives me:
[
{"result": true, "word": "Hi"},
{"result": true, "word": "Bonjour"},
...
]
MY PROBLEM:
Just wondering if there is any better way to write this program with fewer lines. I'm not a fan of for i in range() really. I'm just curious how can I do the list comprehension with for word, lang in item syntax.
zip.zipthem to save iterating over a range, but why not just e.g.result = [{"word": d["word"], result: db.insertIntoSwearWords(d["word"], d["lang"])} for d in data}.