sebiiix
sebiiix

Reputation: 3

How to update dict with multiple results of for loop?

I have an array of arrays:

wordList = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

I want the following output (keeping always the first value):

[{'words': {'word0': 'a', 'word1': 'c', 'word2': 'e'}}]

So far I have tried this solution:

for i in range(0, len(wordList[0])-1):
jsonList[0].update({"words":{"word"+str(i):wordList[0][i]}}

But I receive output just for word0:

[{'words': {'word0': 'x'}}]

What can be changed?

Upvotes: 0

Views: 44

Answers (2)

J Faucher
J Faucher

Reputation: 988

On your MWE, you are missing an identation which would explain some of your issue :

for i in range(0, len(wordList[0])-1):
    jsonList[0].update({"words":{"word"+str(i):wordList[0][i]}}

would be better.

Moreover, you can use the comprehensive dict declaration (newlines not required)

jsonList[0].update({"words":
                       {"word"+str(i):wordList[0][i] for i in range(len(wordList[0]))}
                   }

Which would do all of your job. Please note that range(min,max) will already go from min to max-1. And that you don't even need min if it is 0 as per the doc.

Then consider using f-expressions to get :

{f"word{i}":wordList[0][i] for i in range(len(wordList[0]))}

Which is as pythonic as it could get (as far as I know) The finished code would then be :

jsonList[0].update({"words":{f"word{i}":wordList[0][i] for i in range(len(wordList[0]))}})

Upvotes: 0

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

Based on your comments, I believe this is the solution you're looking for:

first_values_and_keys = [('word'+str(i), el[0]) for i, el in enumerate(wordList)]
words_dict = {k: v for k, v in first_values_and_keys}
jsonList[0]['words'] = words_dict

PS: if you are using python 3.x 'word' + str(i) can become f'word{i}' which is a bit nicer

Upvotes: 1

Related Questions