Python convert list to dict with multiple key value
Question: 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: 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 = None
    
    for item in my_list:
        if '=' in item:
            current_key, value = item.split('=')
    
        my_dict[current_key].append(value)
    
    my_dict = {k: v[0] if len(v) == 1 else 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) if type(v) is list else v)
              for k, v in my_dict.iteritems()]
    print output
    

