0

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.

4
  • Checkout zip. Commented Apr 12, 2021 at 8:13
  • 2
    What's the point of the words and langs lists? You could zip them 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}. Commented Apr 12, 2021 at 8:13
  • Since it seems you have working code and are looking for general improvements, this appears to more appropriate for CodeReview – be sure to check their question guide first, though. Commented Apr 12, 2021 at 8:20
  • Extracting two separate lists of variables isn't helpful since they later get recombined back into their original pairs at the point they're fed into the function. I was thinking zip as well, but it's not necessary given the task. edit Ahh, which is precisely the point @jonrsharpe makes above with more clarity. Commented Apr 12, 2021 at 8:31

1 Answer 1

1

You can use the built-in zip function. For example:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> c = [(i, j) for i, j in zip(a, b)]
>>> c
[(1, 'a'), (2, 'b'), (3, 'c')]

Also, you can do

>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c')]

Which gives the same result.

Sign up to request clarification or add additional context in comments.

3 Comments

When you answer,please provide a specific (to the question) solution, a generic solution is not a good way to answer ;)
@azro thanks for pointing that out, I will be more specific in the future :)
What you're suggestion is I replace third line with res = [db.insertIntoSwearWords(word, lang) for word,lang in zip(words,langs)], that's helpful. but still the code is ugly and I'm trying to write a neat code. Isn't there a better way than parsing word/lang separately and zipping them back?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.