我想将字符串转换为字典我的弦是"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)