如何将字符串转换为字典,第一个单词是值,另外3个单词是键

问题描述 投票:0回答:3
例如,我想将字符串转换为字典 我的绳子是

"Man I Je Ich"

所以字典结果是

{ 'I' : 'Man', 'Je': 'Man', 'Ich': 'Man' }
第一个单词是值,另外 3 个单词是键

python python-3.x dictionary
3个回答
1
投票
您可以将第一个单词和其余单词放在单独的变量中,然后使用

dict

 理解来创建 
dict
:

s = "Man I Je Ich" val, *keys = s.split() data = {k: val for k in keys} # or data = dict.fromkeys(keys, val)


>>> data {'I': 'Man', 'Je': 'Man', 'Ich': 'Man'}
    

0
投票
试试这个哑巴..

string = "Man I Je Ich" #split string to words words = string.split() #get first word as key key = words[0] #remove the key from words del words[0] #create your dictionary dictionary = {} for word in words: dictionary[word] = key print(dictionary)
    

0
投票
这个作品文件:

string = "Man I Je Ich" keys = string.split() data = {key: keys[0] for key in keys[1:]}
    
© www.soinside.com 2019 - 2024. All rights reserved.