简体   繁体   English

自定义列表到字典列表

[英]Custom list of lists into dictionary

I have list of lists and I wish to create a dictionary with length of each element as values. 我有列表列表,我希望创建一个字典,每个元素的长度作为值。 I tried the following: 我尝试了以下方法:

tmp = [['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
tab = []
for line in tmp:
    tab.append(dict((k, len(tmp)) for k in line))

But it gives the output as: 但它给出的输出为:

[{'A': 3, 'B': 3, 'E': 3}, {'B': 3, 'E': 3, 'F': 3}, {'A': 3, 'G': 3}]

What is the modification that I should make to get the output: 我应该对输出进行什么修改:

{['A', 'B', 'E']:3, ['B', 'E', 'F']:3, ['A', 'G']:2}

Thanks in advance. 提前致谢。

AP 美联社

You can't use list objects as dictionary keys, they are mutable and unhashable. 您不能将list对象用作字典键,因为它们是可变的且不可散列。 You can convert them to tuple. 您可以将它们转换为元组。 Also note that you are looping over each sub list. 另请注意,您正在遍历每个子列表。 You can use a generator expression by only looping over the main list: 您可以通过仅遍历主列表来使用生成器表达式:

In [3]: dict((tuple(sub), len(sub)) for sub in tmp)
Out[3]: {('A', 'B', 'E'): 3, ('A', 'G'): 2, ('B', 'E', 'F'): 3}
{tuple(t):len(t) for t in tmp}

Input : 输入:

[['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]

Output : 输出:

{('A', 'G'): 2, ('A', 'B', 'E'): 3, ('B', 'E', 'F'): 3}

Dictionnary does not accept list as key, but tuple Dictionnary不接受列表作为键,但是元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM