Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Convert a list of Tuples into Dictionary

Python | Convert a list of Tuples into Dictionary

Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. 

Examples:

Input : [("akash", 10), ("gaurav", 12), ("anand", 14), 
         ("suraj", 20), ("akhil", 25), ("ashish", 30)]
Output : {'akash': [10], 'gaurav': [12], 'anand': [14], 
          'ashish': [30], 'akhil': [25], 'suraj': [20]}

Input : [('A', 1), ('B', 2), ('C', 3)]
Output : {'B': [2], 'A': [1], 'C': [3]}

Input : [("Nakul",93), ("Shivansh",45), ("Samved",65),
             ("Yash",88), ("Vidit",70), ("Pradeep",52)]
Output : {'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 
            'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}

Input : [('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)]
Output : {'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}

Method 1 : Use of setdefault()

Here we have used the dictionary method setdefault() to convert the first parameter to key and the second to the value of the dictionary. setdefault(key, def_value) function searches for a key and displays its value, and creates a new key with def_value if the key is not present. Using the append function we just added the values to the dictionary. 

Example 1: 

Python3




# Python code to convert into dictionary
 
 
def Convert(tup, di):
    for a, b in tup:
        di.setdefault(a, []).append(b)
    return di
 
 
# Driver Code
tups = [("akash", 10), ("gaurav", 12), ("anand", 14),
        ("suraj", 20), ("akhil", 25), ("ashish", 30)]
dictionary = {}
print(Convert(tups, dictionary))


Output:

{'akash': [10], 'gaurav': [12], 'anand': [14], 
 'ashish': [30], 'akhil': [25], 'suraj': [20]}

Time Complexity: O(n), where n is the length of the dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list

Example 2: 

Python3




# Python code to convert into dictionary
list_1 = [("Nakul", 93), ("Shivansh", 45), ("Samved", 65),
          ("Yash", 88), ("Vidit", 70), ("Pradeep", 52)]
dict_1 = dict()
 
for student, score in list_1:
    dict_1.setdefault(student, []).append(score)
print(dict_1)


Output:

{'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}

Method 2 : Use of dict() method

Example 1: 

Python3




# Python code to convert into dictionary
def Convert(tup, di):
    di = dict(tup)
    return di
     
# Driver Code
tups = [("akash", 10), ("gaurav", 12), ("anand", 14),
    ("suraj", 20), ("akhil", 25), ("ashish", 30)]
dictionary = {}
print (Convert(tups, dictionary))


Output:

{'anand': 14, 'akash': 10, 'akhil': 25, 
 'suraj': 20, 'ashish': 30, 'gaurav': 12}

Time complexity: O(n), where n is the number of key-value pairs in the input tuple list. 

Auxiliary space: O(n), where n is the number of key-value pairs in the input tuple list. 

Example 2: 

Python3




# Python code to convert into dictionary
 
print(dict([('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)]))


Output:

{'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}

Time complexity: O(1)
Auxiliary space: O(1)

Method 3:

You can use the itertools.groupby function from the itertools module to convert a list of tuples into a dictionary, where the keys are the unique values in the list and the values are lists of tuples that have the same value.

Here is an example of how to use itertools.groupby to achieve this:

Python3




from itertools import groupby
 
 
def convert_to_dict(tuple_list):
    # Group the tuples by their first element (the key)
    groups = groupby(tuple_list, key=lambda x: x[0])
 
    # Create an empty dictionary
    dictionary = {}
 
    # Iterate over the groups
    for key, group in groups:
        # Extract the second element of each tuple in the group and add it to the dictionary as the value for the key
        dictionary[key] = [tuple[1] for tuple in group]
 
    return dictionary
 
 
# Test the function
tuple_list = [("akash", 10), ("gaurav", 12), ("anand", 14),
              ("suraj", 20), ("akhil", 25), ("ashish", 30)]
print(convert_to_dict(tuple_list))  # {'akash':


Output

{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}

Time complexity: O(n log n + k).
Auxiliary space: O(n)

Method 4: Using the setdefault() method

Algorithm:

  1. Initialize an empty dictionary and a list of tuples.
  2. Traverse the tuples using a for loop.
  3. For each tuple, extract the key and value and use the setdefault() method to add it to the dictionary.
  4. The setdefault() method sets the value of the key to the given value if the key is not already in the dictionary, else it returns the value of the key.
  5. Return the final dictionary.

Python3




tups = [("akash", 10), ("gaurav", 12), ("anand", 14),
        ("suraj", 20), ("akhil", 25), ("ashish", 30)]
dictionary = {}
for key, val in tups:
    dictionary.setdefault(key, val)
print(dictionary)
# This code is contributed by Vinay Pinjala.


Output

{'akash': 10, 'gaurav': 12, 'anand': 14, 'suraj': 20, 'akhil': 25, 'ashish': 30}

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary Space: O(n), where n is the number of tuples in the list. The dictionary created will have n key-value pairs.

Method 5: Using a loop to add tuples to the dictionary

  1. Create an empty dictionary.
  2. Iterate over each tuple in the tuple list.
  3. Check if the first element of the tuple (the key) is already in the dictionary.
  4. If the key is not in the dictionary, add it and set the value as a list containing the second element of the tuple.
  5. If the key is already in the dictionary, append the second element of the tuple to the existing list of values for that key.
  6. Return the completed dictionary.

Python3




def convert_to_dict(tuple_list):
    # Create an empty dictionary
    dictionary = {}
 
    # Iterate over each tuple in the list
    for tuple in tuple_list:
        # Check if the key is already in the dictionary
        if tuple[0] in dictionary:
            # If the key is already in the dictionary, append the value to the existing list
            dictionary[tuple[0]].append(tuple[1])
        else:
            # If the key is not in the dictionary, add it and set the value as a new list
            dictionary[tuple[0]] = [tuple[1]]
 
    # Return the completed dictionary
    return dictionary
 
 
# Test the function
tuple_list = [("akash", 10), ("gaurav", 12), ("anand", 14),
              ("suraj", 20), ("akhil", 25), ("ashish", 30)]
# {'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}
print(convert_to_dict(tuple_list))


Output

{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list, to store the dictionary.

Method 6 : use the dict() constructor and a list comprehension.

  1. Here is the step-by-step approach using dict() constructor and list comprehension:
  2. Create a list comprehension that generates a tuple of the form (key, value) for each tuple in the input list.
  3. Pass the list comprehension as an argument to the dict() constructor to create a dictionary.

Python3




def convert_to_dict(tuple_list):
    # Create a dictionary using the dict() constructor and a list comprehension
    dictionary = dict((key, value) for key, value in tuple_list)
 
    # Return the completed dictionary
    return dictionary
 
 
tuple_list = [("akash", 10), ("gaurav", 12), ("anand", 14),
              ("suraj", 20), ("akhil", 25), ("ashish", 30)]
# {'akash': 10, 'gaurav': 12, 'anand': 14, 'suraj': 20, 'akhil': 25, 'ashish': 30}
print(convert_to_dict(tuple_list))


Output

{'akash': 10, 'gaurav': 12, 'anand': 14, 'suraj': 20, 'akhil': 25, 'ashish': 30}

Time complexity: O(n) because we iterate over each tuple in the list once to create the list comprehension. 
Auxiliary space: O(n) because we create a dictionary with n keys and values.:

RELATED ARTICLES

Most Popular

Recent Comments