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?
You can use dict understanding :
data = {smallItem:smallItem for smallItem in bigList}
You can also use dict and generator expression :
dict
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 .
json.dumps
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}
Source: https://habr.com/ru/post/980341/More articles:Generating a 4096-bit RSA key is much slower than 2048-bit using Jsch - javaException when using server route and onBeforeAction - javascriptAccess to Meteor.userId from outside a method / post - javascriptUnable to copy my object and change values ββ- javaCosts of threads and closures in Java 8 - javaVertical Stretch List Elements - javascriptFlexible custom layout with CSS (maybe JS if necessary) - javascriptHow to send an HTTPS request using Retrofit? - androidHow to return an object instead of a response string using nock? - javascriptCreate a variable in swift with a dynamic name - variablesAll Articles