Singleline for-loop to create a dictionary?

I am creating a dictionary (which I will later make into a JSON string). I will build it like this:

data = {} for smallItem in bigList: data[smallItem] = smallItem 

How can I do this for one line of the loop?

+6
source share
2 answers

You can use dict understanding :

 data = {smallItem:smallItem for smallItem in bigList} 

You can also use dict and generator expression :

 data = dict((smallItem, smallItem) for smallItem in bigList) 

But understanding the dict will be faster.

As for converting this to a JSON string, you can use json.dumps .

+13
source

In fact, in this particular case, you do not even need to understand the dictionary, since you are using duplicate key / value pairs.

 >>> bigList = [1, 2, 3, 4, 5] >>> dict(zip(bigList, bigList)) {1: 1, 2: 2, 3: 3, 4: 4, 5: 5} 
+3
source

Source: https://habr.com/ru/post/980341/


All Articles