Single line for-loop to build a dictionary?

Question:

I’m constructing a dictionary (which I’ll later make into a JSON string). I construct it like this:

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

How can I make that for loop one line?

Asked By: easythrees

||

Answers:

You can use a dict comprehension:

data = {smallItem:smallItem for smallItem in bigList}

You might also use dict and a generator expression:

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

But the dict comprehension will be faster.

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

Answered By: user2555451

Actually in this specific case you don’t even need a dictionary comprehension 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}
Answered By: jamylak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.