Reading Time: 1 minutes
List of Tuples into a Dictionary in Python
List of Tuples into a Dictionary: Given a list of 2-element tuples such as [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)], write a Python program to convert this data structure into a dictionary with first elements of the tuples as keys and second elements compose the list associated with the keys like this: {1: [1, 2, 3], 2: [1, 2, 3]}.
List of Tuples into a Dictionary
listOne = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)] dictionaryOne = dict() for key, value in listOne: dictionaryOne.setdefault(key, []).append(value) print(dictionaryOne) # {1: [1, 2, 3], 2: [1, 2, 3]}
Here's more on how to use setdefault() function of dictionaries.
# dict1.setdefault(key[,value]) -> dict1.get(key,value), also set dict1[key]=value if key not in dict1 # If the key is present in the dictionary, then return the corresponding value. Else, insert the key into the dictionary with its value as provided, and return the value. An example should make it clear. >>> IndianCricketTeam = dict(batsman = "V. Kohli", bowler = "B. Kumar") >>> IndianCricketTeam.setdefault('batsman', 'S. Tendulkar') 'V. Kohli' >>> IndianCricketTeam.setdefault('finisher', 'M.S. Dhoni') 'M.S. Dhoni'