我有一个类似下面的列表,并希望将其转换为dict
my_list = ['key1=value1', 'key2=value2', 'key3=value3-1', 'value3-2', 'value3-3', 'key4=value4', 'key5=value5', 'value5-1', 'value5-2', 'key6=value6']
如何将上面的列表转换为dict类似下面的内容
my_dict = {
'key1': 'value1',
'key2': 'value2',
'key3': ['value3-1', 'value3-2', 'value3-3'],
'key4': 'value4',
'key5': ['value5', 'value5-1', 'value5-2'],
'key6': 'value6'
}
答案 0 :(得分:3)
这是一个可能的解决方案:
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)
出于好奇,如果您的输入是字典,获取列表将是微不足道的:
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
答案 1 :(得分:2)
有几种方法,这是一个: 编辑:我的第一个解决方案为每个值提供了一个列表,但是当一个键的值不止一个时,您只需要一个列表。
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)
给出:
{'key1': 'value1',
'key2': 'value2',
'key3': ['value3-1', 'value3-2', 'value3-3'],
'key4': 'value4',
'key5': ['value5', 'value5-1', 'value5-2'],
'key6': 'value6'}
您可能希望通过检查current_key
是否为None
来使其更加健壮。我会把它留给你。