简体   繁体   English

Python:使用[0] =键和[1:] =值从列表创建字典

[英]Python: Create Dictionary From List with [0] = Key and [1:]= Values

I am using the permutations function from itertools , and wish to convert the returned list to a dictionary, with the first element (the original sequence) as Key and all possible combinations of this sequence as its corresponding Values. 我正在使用itertools的permutations函数,并希望将返回的列表转换为字典,其中第一个元素(原始序列)为Key,并且此序列的所有可能组合为其对应的Values。

For instance, output for 'cups' and 'pups' looks like this: 例如,“ cups”和“ pups”的输出如下所示:

['cups', 'cusp', 'cpus', 'cpsu', 'csup', 'cspu', 'ucps', 'ucsp', 'upcs', 'upsc', 'uscp',
'uspc', 'pcus', 'pcsu', 'pucs', 'pusc', 'pscu', 'psuc', 'scup', 'scpu', 'sucp', 'supc', 
'spcu', 'spuc']

['pups', 'pusp', 'ppus', 'ppsu', 'psup', 'pspu', 'upps', 'upsp', 'upps', 'upsp', 'uspp', 
'uspp', 'ppus', 'ppsu', 'pups', 'pusp', 'pspu', 'psup', 'spup', 'sppu', 'supp', 'supp',  
'sppu', 'spup']

From this, I want: 由此,我想要:

{'cups': ['cusp', 'cpus', 'cpsu', 'csup'...], 'pups': ['pusp', 'ppus', 'ppsu'...]}

You can use dictionary expression 您可以使用字典表达

data = [['cups', 'cusp', 'cpus', 'cpsu', 'csup', 'cspu',],
        ['pups', 'pusp','upsp', 'upps', 'upsp', 'uspp']]

result = {each[0]:each[1:] for each in data}           
print result

Yields: 产量:

{'pups': ['pusp', 'upsp', 'upps', 'upsp', 'uspp'], 
'cups': ['cusp', 'cpus', 'cpsu', 'csup', 'cspu']}

暂无
暂无

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

相关问题 从 Python 中的键列表和值的多列表创建字典 - Create a dictionary from a list of key and multi list of values in Python 在 python 中创建一个字典,其中包含 python 中的键和值列表 - create a dictionary in python with a key and a list of values in python 从嵌套字典创建值列表 Python - Create a list of values from nested dictionary Python Python-从两个列表创建字典,列表名称为键,列表元素为值 - Python - Create a dictionary from two lists with list name as key and list elements as values 如何用Python中的键列表和值字典创建字典? - How to create a dictionary from a list of keys and a dictionary of values in Python? 如何在 Python 中的字典列表中使用另一个键列表中的值在字典中创建一个新键? - How to create a new key in dictionary with value from another key list from a list of dictionary in Python? 从两个列表创建字典,并添加具有相同键的值 - create dictionary from two list with the addition of values with same key PySpark - 从字典中创建一个 Dataframe,其中包含每个键的值列表 - PySpark - Create a Dataframe from a dictionary with list of values for each key 如何使用字典中的相同键创建值列表 - How to create a list of values with the same key from a dictionary Python - 根据给定的键数动态创建新字典中的键数:值:另一个字典中的值 - Python - dynamically create number of key:values in a new dictionary, based on given number of key:values from another dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM