Open In App

Python | Convert list of tuple into dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task.

Input:
indices = ['x','y','z','w','t','r']
relation =[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Output:
{'x': ['y', 'z', 'w'], 'y': ['x', 'z', 'w'], 'z': ['x', 'y', 'w'], 
'w': ['x', 'y', 'z'], 't': [], 'r': []}

Method #1: Using iteration is the easiest way to solve any task 

Python3




#Python code to convert list of tuple into dictionary showing
#relation of every element from first list to every other element in the list.
 
#List initialization
indices = ['x','y','z','w','t','r']
relation =[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
#dictionary initialization
Output = {}
 
#Iteration
for elem in indices:
     temp= []
     for rel in relation:
          if elem in rel:
               if elem == rel[0]:
                    temp.append(rel[1])
               else:
                    temp.append(rel[0])
      
     Output[elem] = temp
     temp = []
 
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(Output)


Output :
Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'w': ['x', 'y', 'z'], 'r': [], 'x': ['y', 'z', 'w'], 't': [], 
'y': ['x', 'z', 'w'], 'z': ['x', 'y', 'w']}

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

Method #2: Using networkx is the most simplest and shortest way to convert list of tuple into dictionary 

Python3




#Python code to convert list of tuple into dictionary showing
#relation of every element from first list to every other element in the list.
 
#Importing
import networkx as nx
 
#List initialization
indices = ['x','y','z','w','t','r']
relation =[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
#dictionary initialization
Output = {}
 
#Using networkx to solve
temp=nx.Graph(relation)
temp.add_nodes_from(indices)
Output = nx.to_dict_of_lists(temp)
 
#Printing
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(Output)


Output :
Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'w': ['x', 'y', 'z'], 'r': [], 'x': ['y', 'z', 'w'], 't': [], 
'y': ['x', 'z', 'w'], 'z': ['x', 'y', 'w']}

Method #3: Using itertools and groupby is another way to convert list of tuple into dictionary. 

Python3




#Python code to convert list of tuple into dictionary showing
#relation of every element from first list to every other element in the list.
 
#Importing
from itertools import groupby
from operator import itemgetter
 
#List initialization
indices = ['x','y','z','w','t','r']
relation =[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
#Using itertools.groupby and maps
edge = relation + [tuple(reversed(pair)) for pair in relation]
st = itemgetter(0)
end = itemgetter(1)
groups = groupby(sorted(edge), key=st)
mapping = {vertex: list(map(end, edges)) for vertex, edges in groups}
from collections import defaultdict
 
#Output list
Output = defaultdict(list, mapping)
Output = dict(mapping)
Output.update({vertex: [] for vertex in indices if vertex not in mapping})
 
#Printing
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(Output)


Output :
Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'w': ['x', 'y', 'z'], 'r': [], 'x': ['y', 'z', 'w'], 't': [], 
'y': ['x', 'z', 'w'], 'z': ['x', 'y', 'w']}

Method#4: Using Recursive method.

Algorithm:
The given Python code converts a list of tuples into a dictionary by creating a dictionary with keys as every element of the input list and the corresponding value as a list of all elements in the input list that are related to the key element. Here is the algorithm for the same:

  1. Define a function named “convert_to_dict_recursive” that takes two arguments, “indices” and “relation”. “indices” is the list of all elements that need to be converted into keys of the dictionary, and “relation” is the list of tuples showing the relation between these elements.
  2. If the length of the “indices” list is zero, return an empty dictionary.
  3. Otherwise, take the first element of the “indices” list and initialize an empty list named “curr_list”.
  4. Iterate through every tuple in the “relation” list, and if the current element is present in the tuple, add the other element of the tuple to the “curr_list”.
  5. Recursively call the “convert_to_dict_recursive” function with the rest of the “indices” list (excluding the first element) and the “relation” list.
  6. Create a new empty dictionary named “res”.
  7. Set the value of the current element (the first element of “indices”) in the “res” dictionary to “curr_list”.
  8. Return the “res” dictionary.

Python3




#Python code to convert list of tuple into dictionary showing
#relation of every element from first list to every other element in the list.
def convert_to_dict_recursive(indices, relation):
    if len(indices) == 0:
        return {}
    else:
        curr_elem = indices[0]
        curr_list = []
        for rel in relation:
            if curr_elem in rel:
                if curr_elem == rel[0]:
                    curr_list.append(rel[1])
                else:
                    curr_list.append(rel[0])
        res = convert_to_dict_recursive(indices[1:], relation)
        res[curr_elem] = curr_list
        return res
 
#List initialization
indices = ['x','y','z','w','t','r']
relation =[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
res = convert_to_dict_recursive(indices, relation)
 
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(res)


Output

Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'r': [], 't': [], 'w': ['x', 'y', 'z'], 'z': ['x', 'y', 'w'], 'y': ['x', 'z', 'w'], 'x': ['y', 'z', 'w']}

The time complexity of this algorithm is O(n^2), where n is the number of elements in the “indices” list. This is because, in the worst case, for each element in the “indices” list, we need to iterate through every tuple in the “relation” list. 

The auxiliary space of the algorithm is also O(n^2), since the resulting dictionary can have up to n keys, and each key can have a list of up to n-1 values.

Method 5: Using a dictionary comprehension. 

Here are the steps for this approach:

  1. Create an empty dictionary to store the results.
  2. Loop through the list of tuples and for each tuple, extract the two elements.
  3. If the first element is already a key in the dictionary, append the second element to its value list.
  4. Otherwise, create a new key-value pair where the key is the first element and the value is a list containing the second element.
  5. Return the resulting dictionary.

Python3




def convert_to_dict_comprehension(indices, relation):
    d = {}
    for a, b in relation:
        d.setdefault(a, []).append(b)
        d.setdefault(b, []).append(a)
    return d
 
# List initialization
indices = ['x', 'y', 'z', 'w', 't', 'r']
relation = [('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
res = convert_to_dict_comprehension(indices, relation)
 
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(res)


Output

Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'x': ['y', 'z', 'w'], 'y': ['x', 'z', 'w'], 'z': ['x', 'y', 'w'], 'w': ['x', 'y', 'z']}

Time complexity: O(n), where n is the length of the list of tuples.
Auxiliary space: O(n), where n is the length of the list of tuples.

Method 6: Using heapq:

Algorithm:

  1. Sort the list of tuples in descending order of the second element of each tuple.
  2. Create an empty dictionary.
  3. Iterate through the sorted list of tuples and add each tuple to the dictionary as a key-value pair.
  4. Return the completed dictionary.

Python3




import heapq
from collections import defaultdict
 
# List initialization
indices = ['x','y','z','w','t','r']
relation = [('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
 
# Initialize the output dictionary
Output = defaultdict(list)
 
# Convert indices to a set for faster membership testing
indices_set = set(indices)
 
# Add edges to the heap in both directions
heap = relation + [(v, u) for (u, v) in relation]
 
# Loop through the heap and add edges to the output dictionary
while heap:
    edge = heapq.heappop(heap)
    if edge[0] in indices_set:
        Output[edge[0]].append(edge[1])
 
# Add empty lists for indices that have no edges
for vertex in indices:
    if vertex not in Output:
        Output[vertex] = []
 
# Convert Output to dict
Output = dict(Output)
 
# Print the results
print("Initial list of tuple is :")
print(relation)
print("Converted dictionary of list :")
print(Output)
#This code is contributed by Rayudu.


Output

Initial list of tuple is :
[('x', 'y'), ('x', 'z'), ('x', 'w'), ('y', 'z'), ('y', 'w'), ('z', 'w')]
Converted dictionary of list :
{'x': ['y', 'w', 'z'], 'w': ['z', 'y', 'x'], 'y': ['w', 'x', 'z'], 'z': ['w', 'x', 'y'], 't': [], 'r': []}

Time Complexity:
The time complexity of sorting a list of n elements is O(nlogn) using the Timsort algorithm used by Python’s built-in sorted() function. The time complexity of iterating through a list of n elements and adding each element to a dictionary is O(n). Therefore, the overall time complexity of the algorithm is O(nlogn).

Space Complexity:
The space complexity of the algorithm depends on the size of the input list. The space required to store the sorted list of tuples is O(n), and the space required to store the dictionary is also O(n). Therefore, the overall space complexity of the algorithm is O(n).



Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads