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



我想将字符串转换为字典我的弦是"Man I Je Ich"所以dictionary result是

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

第一个字是value,另外三个字是keys

您可以将第一个单词和其余部分放在单独的变量中,然后使用dict推导来创建dict:

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

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

这个作品文件:

string = "Man I Je Ich"
keys = string.split()
data = {key: keys[0] for key in keys[1:]}

试试这个笨蛋…

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)  

相关内容

  • 没有找到相关文章

最新更新