[英]Convert a list of str and lists to dict
在Python中,如何将包含字符串和具有两个值的列表的列表转换为字典,使键为字符串,而值为列表的列表,使每个列表的第一个值为键。
例如,我当前拥有的列表是:
['A', ['A', 1], 'B', ['B',1], ['B',2], 'C', ['C', 1], ['C',2], ['C',3]]
我想要字典:
{'A': [['A', 1]], 'B': [['B',1], ['B',2]], 'C': [['C',1], ['C',2],
['C',3]]}
谢谢。
编辑:字符串后面的列表数是任意的。
这样,无论列表的顺序如何,它都会精确选择您要查找的内容。
def new(list_):
new_dic = {x:[y for y in list_ if type(y) == list and y[0] == x] for x in list_ if type(x) == str}
print(new_dic)
new(['A', ['A', 1], ['A',2], 'B', ['B',1], ['B',2], 'C', ['C', 1], ['C',2]])
d = {l: [] for l in mylist if type(l) is str}
for l in mylist:
if type(l) is list:
d[l[0]].append(l)
您可以尝试defaultdict
from collections import defaultdict
my_dict = defaultdict(list)
my_list = ['A', ['A', 1], ['A',2], 'B', ['B',1], ['B',2], 'C', ['C', 1], ['C',2]]
for index in my_list:
if len(index) > 1:
my_dict[index[0]].append(index)
列表中的字符串值似乎无关紧要。 根据提供的列表的当前结构和所需的输出,您可以仅检查列表中的列表,并且使用defaultdict构造,您可以简单地相应地构建字典:
from collections import defaultdict
l = ['A', ['A', 1], 'B', ['B',1], ['B',2], 'C', ['C', 1], ['C',2], ['C',3]]
d = defaultdict(list)
for data in l:
if type(data) is list:
d[data[0]].append(data)
输出:
defaultdict(<class 'list'>, {'A': [['A', 1]], 'C': [['C', 1], ['C', 2], ['C', 3]], 'B': [['B', 1], ['B', 2]]})
因此,在这里, defaultdict
将采用列表作为其默认集合值。 因此,添加新密钥时,默认值将是列表。 遍历列表时,只需检查列表中数据的类型。 当找到list
,将list
的第一个值作为键将其插入到字典中,然后将列表附加为值。 它应该为您提供所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.