简体   繁体   中英

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.

For instance, output for 'cups' and 'pups' looks like this:

['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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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