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:
- 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.
- If the length of the "indices" list is zero, return an empty dictionary.
- Otherwise, take the first element of the "indices" list and initialize an empty list named "curr_list".
- 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".
- Recursively call the "convert_to_dict_recursive" function with the rest of the "indices" list (excluding the first element) and the "relation" list.
- Create a new empty dictionary named "res".
- Set the value of the current element (the first element of "indices") in the "res" dictionary to "curr_list".
- 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)
OutputInitial 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:
- Create an empty dictionary to store the results.
- Loop through the list of tuples and for each tuple, extract the two elements.
- If the first element is already a key in the dictionary, append the second element to its value list.
- Otherwise, create a new key-value pair where the key is the first element and the value is a list containing the second element.
- 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)
OutputInitial 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:
- Sort the list of tuples in descending order of the second element of each tuple.
- Create an empty dictionary.
- Iterate through the sorted list of tuples and add each tuple to the dictionary as a key-value pair.
- 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.
OutputInitial 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).
Similar Reads
Convert a list of Tuples into Dictionary - Python
Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
3 min read
Convert Two Lists into a Dictionary - Python
We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
3 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDi
5 min read
Convert Lists to Nested Dictionary - Python
The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary. For example, given the lists a = ["gfg", "is", "best"], b = ["ratings", "price", "score"], and c = [5, 6, 7], the g
3 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different met
3 min read
Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties:Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for furt
2 min read
Python - Converting list string to dictionary
Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val
3 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
How To Convert Generator Object To Dictionary In Python
We are given a generator object we need to convert that object to dictionary. For example, a = (1, 2, 3), b = ('a', 'b', 'c') we need to convert this to dictionary so that the output should be {1: 'a', 2: 'b', 3: 'c'}.Using a Generator ExpressionA generator expression can be used to generate key-val
3 min read
Convert Unicode String to Dictionary in Python
Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is convert
2 min read