简体   繁体   English

如何从python中的列表列表中创建字典?

[英]How to create a dictionary out of a list of lists in python?

Let's suppose I have the following list made out of lists 假设我的清单中有以下清单

list1 = [['a','b'],['a'],['b','c'],['c','d'],['b'], ['a','d']]

I am wondering if there is a way to convert every element of list1 in a dictionary where all the new dictionaries will use the same key. 我想知道是否有一种方法可以转换字典中所有新字典将使用相同键的list1每个元素。 Eg: if ['a'] gets to be {'a':1} , and ['b'] gets to be {'b':2} , I would like for all keys a the value of 1 and for all keys b the value of 2 . 例如:如果['a']获取要{'a':1}['b']获取要{'b':2}我想为所有键a的值1并用于所有键b的值为2 Therefore, when creating the dictionary of ['a','b'] , I would like to turn into {'a':1, 'b':2} . 因此,在创建['a','b']字典时,我想变成{'a':1, 'b':2}

What I have found so far are ways to create a dictionary out of lists of lists but using the first element as the key and the rest of the list as the value: 到目前为止,我发现了从列表列表中创建字典的方法,但是使用第一个元素作为键,而将列表的其余部分用作值:

Please note that's not what I am interested in. The result I would want to obtain from list1 is something like: 请注意,这不是我感兴趣的。我想要从list1获得的结果是这样的:

dict_list1 = [{'a':1,'b':2}, {'a':1}, {'b':2,'c':3}, {'c':3,'d':4}, {'b':2}, {'a':1,'d':4}]

I am not that interested in the items being that numbers but in the numbers being the same for each different key. 我对那个数字的项目不感兴趣,但是对每个不同的键的数字都是相同的。

You need to declare your mapping first: 您需要先声明您的映射:

mapping = dict(a=1, b=2, c=3, d=4)

Then, you can just use dict comprehension: 然后,您可以使用dict理解:

[{e: mapping[e] for e in li} for li in list1]
# [{'a': 1, 'b': 2}, {'a': 1}, {'b': 2, 'c': 3}, {'c': 3, 'd': 4}, {'b': 2}, {'a': 1, 'd': 4}]

Using chain and OrderedDict you can do auto mapping 使用chainOrderedDict可以进行自动映射

from itertools import chain
from collections import OrderedDict

list1 = [['a','b'],['a'],['b','c'],['c','d'],['b'], ['a','d']]
# do flat list for auto index
flat_list = list(chain(*list1))
# remove duplicates
flat_list = list(OrderedDict.fromkeys(flat_list))
mapping = {x:flat_list.index(x)+1 for x in set(flat_list)}

[{e: mapping[e] for e in li} for li in list1]

在这里,尝试一下ord()同样适用于大写字母和小写字母:

[{e: ord(e)%32 for e in li} for li in list1]

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

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