Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line for-loop to build a dictionary?

People also ask

How do you make a dictionary one line?

Python Update Dictionary in One Line Solution: Use the square bracket notation dict[key] = value to create a new mapping from key to value in the dictionary. There are two cases: The key already existed before and was associated to the old value_old .

Can you do a for loop for dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

How do you add a loop to a dictionary?

You can add keys and to dict in a loop in python. Add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.


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}