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 .
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With