How to convert a list to a dictionary in Python?

To convert a list to a dictionary in Python, you need to define the mapping between keys and values based on your requirements. Here are a couple of approaches to convert a list to a dictionary:

Using a List of Tuples: If your list contains tuples with key-value pairs, you can directly convert the list to a dictionary using the dict() function. Each tuple should have exactly two elements, where the first element is treated as the key and the second element as the value.

Using List Indexing: If your list contains values without explicit keys, you can use the index positions of the values to create keys. The keys can be generated dynamically using a range or a specific pattern, and the list elements will be mapped to those keys.

In the second approach, the enumerate() function is used to generate an index along with each list element. The index is then converted to a string using str(i), which serves as the key in the dictionary. The corresponding list element is assigned as the value.

These examples demonstrate two common ways to convert a list to a dictionary in Python. Depending on your specific requirements and the structure of your list, you may need to adapt the approach accordingly.

my_list = ['John', 30, 'USA']
my_dict = {str(i): value for i, value in enumerate(my_list)}
# Output: {'0': 'John', '1': 30, '2': 'USA'}
my_list = [('name', 'John'), ('age', 30), ('country', 'USA')]
my_dict = dict(my_list)
# Output: {'name': 'John', 'age': 30, 'country': 'USA'}

Related Questions You Might Be Interested