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.
1
solved Python convert list to dict with multiple key value [closed]