PYTHON
Convert List of Tuples/Lists to Dictionary in Python
Learn to efficiently convert a list of (key, value) pairs (either tuples or lists) into a Python dictionary, and how to reverse the process for flexible data representation.
# 1. Convert a list of tuples to a dictionary
list_of_tuples = [('name', 'Alice'), ('age', 30), ('city', 'New York')]
data_dict_from_tuples = dict(list_of_tuples)
print(f"Dict from tuples: {data_dict_from_tuples}")
# 2. Convert a list of lists (key-value pairs) to a dictionary
list_of_lists = [['product', 'Laptop'], ['price', 1200], ['currency', 'USD']]
data_dict_from_lists = dict(list_of_lists)
print(f"Dict from lists: {data_dict_from_lists}")
# 3. Convert a dictionary back to a list of tuples
dict_to_convert = {'id': 101, 'status': 'active', 'timestamp': '2023-01-15'}
list_of_items = list(dict_to_convert.items())
print(f"List of tuples from dict: {list_of_items}")
# 4. Convert a dictionary back to a list of (key, value) lists
list_of_key_value_lists = [[k, v] for k, v in dict_to_convert.items()]
print(f"List of lists from dict: {list_of_key_value_lists}")
How it works: This snippet demonstrates the fundamental conversions between lists of key-value pairs (represented as tuples or lists) and Python dictionaries. The built-in `dict()` constructor can directly accept an iterable of key-value pair iterables (like a list of tuples or a list of lists) to create a dictionary. To reverse the process, the `.items()` method of a dictionary returns a view of its key-value pairs as tuples, which can then be converted to a list of tuples using `list()`. A list comprehension can be used to convert these tuples into lists of lists if that specific format is required.