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?
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
.
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}
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?
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
.
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}