如何使用序列将python列表转换为python字典

时间:2022-09-01 20:55:46

Can somebody tell me how to convert list1 to dic_list with all keys equal to the sequence of elements of the list and all values in dictionary equal to the elements in list split by ','?

有人可以告诉我如何将list1转换为dic_list,所有键都等于列表元素的序列,字典中的所有值都等于列表中的元素','?


input:

输入:

list1 = ['1,2,3','4,5,6','7,8']

expected output:

预期产量:

dic_list = {0:['1','2','3'],1:['4','5','6'],2:['7','8']}

I created a new list2:

我创建了一个新的list2:

list2 = []
for num in range(0,len(list1)):
    list2.append(num)

dic_list = dict(zip(list2,list1))

But my output is:

但我的输出是:

dic_list = {0:'1,2,3',1:'4,5,6',2:'7,8'}

3 个解决方案

#1


4  

You can try this:

你可以试试这个:

list1 = ['1,2,3','4,5,6','7,8']
final_list = {i:a.split(',') for i, a in enumerate(list1)}

Output:

输出:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

Or, using the builting dict function:

或者,使用构建dict函数:

final_list = dict(enumerate(map(lambda x:x.split(','), list1)))

Output:

输出:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

#2


3  

You need to split the strings to form lists:

您需要将字符串拆分为表单列表:

list1 = ['1,2,3', '4,5,6', '7,8']

dic_list = {k: v.split(',') for k, v in enumerate(list1)}
dic_list

output:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

#3


0  

You can enumerate to get the key and split the list with ',' to get desired value.

您可以枚举以获取密钥并使用“,”拆分列表以获得所需的值。

list1 = ['1,2,3', '4,5,6', '7,8']
Output = {key: value.split(',') for key, value in enumerate(list1)} 
Output

#1


4  

You can try this:

你可以试试这个:

list1 = ['1,2,3','4,5,6','7,8']
final_list = {i:a.split(',') for i, a in enumerate(list1)}

Output:

输出:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

Or, using the builting dict function:

或者,使用构建dict函数:

final_list = dict(enumerate(map(lambda x:x.split(','), list1)))

Output:

输出:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

#2


3  

You need to split the strings to form lists:

您需要将字符串拆分为表单列表:

list1 = ['1,2,3', '4,5,6', '7,8']

dic_list = {k: v.split(',') for k, v in enumerate(list1)}
dic_list

output:

{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}

#3


0  

You can enumerate to get the key and split the list with ',' to get desired value.

您可以枚举以获取密钥并使用“,”拆分列表以获得所需的值。

list1 = ['1,2,3', '4,5,6', '7,8']
Output = {key: value.split(',') for key, value in enumerate(list1)} 
Output