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', 'v
Solution 1:
Here's a possible solution:
from collections import defaultdict
import pprint
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 = defaultdict(list)
current_key = Nonefor item in my_list:
    if'='in item:
        current_key, value = item.split('=')
    my_dict[current_key].append(value)
my_dict = {k: v[0] iflen(v) == 1else v for k, v in my_dict.iteritems()}
pprint.pprint(my_dict)
Out of curiosity, if your input was a dictionary, getting a list would be trivial:
from collections import defaultdict
my_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': ['value3-1', 'value3-2', 'value3-3'],
    'key4': 'value4',
    'key5': ['value5', 'value5-1', 'value5-2'],
    'key6': 'value6'
}
output = ["{0}={1}".format(k, ', '.join(v) iftype(v) islistelse v)
          for k, v in my_dict.iteritems()]
print output
Solution 2:
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 = Nonefor 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 listifnotisinstance(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.
Post a Comment for "Python Convert List To Dict With Multiple Key Value"