Mudasir Mirza Mudasir Mirza - 3 months ago 13
Python Question

Python convert list to dict with multiple key value

I have a list something like below and want to convert it to dict

my_list = ['key1=value1', 'key2=value2', 'key3=value3-1', 'value3-2', 'value3-3', 'key4=value4', 'key5=value5', 'value5-1', 'value5-2', 'key6=value6']


How can I convert above list to dict something like below

my_dict = {
'key1': 'value1',
'key2': 'value2',
'key3': ['value3-1', 'value3-2', 'value3-3'],
'key4': 'value4',
'key5': ['value5', 'value5-1', 'value5-2'],
'key6': 'value6'
}

Answer

Several ways to do this, this is one: EDIT: my first solution gave a list for every value, but you only require a list when there is more than one value for a key.

my_list = ['key1=value1', 'key2=value2', 'key3=value3-1', 'value3-2', 'value3-3', 'key4=value4', 'key5=value5', 'value5-1', 'value5-2', 'key6=value6']

my_dict = {}
current_key = None
for item in my_list:
    if '=' in item:
        current_key, value = item.split('=')
        # This puts a string as the value
        my_dict[current_key] = value  
    else:
        # Check if the value is already a list
        if not isinstance(my_dict[current_key], list):
            # If value is not a list, create one
            my_dict[current_key] = [my_dict[current_key]]

        my_dict[current_key].append(item)

import pprint
pprint.pprint(my_dict)

Gives:

{'key1': 'value1',
 'key2': 'value2',
 'key3': ['value3-1', 'value3-2', 'value3-3'],
 'key4': 'value4',  
 'key5': ['value5', 'value5-1', 'value5-2'],
 'key6': 'value6'}

You might wish to make it more robust by checking if current_key is None. I'll leave that to you.