【发布时间】:2021-09-16 18:51:48
【问题描述】:
例如,我想将字符串转换为字典
我的字符串是"Man I Je Ich"
所以字典结果是
{
'I' : 'Man',
'Je': 'Man',
'Ich': 'Man'
}
第一个词是值,另外 3 个词是键
【问题讨论】:
-
到目前为止你尝试了什么?
标签: python python-3.x dictionary
例如,我想将字符串转换为字典
我的字符串是"Man I Je Ich"
所以字典结果是
{
'I' : 'Man',
'Je': 'Man',
'Ich': 'Man'
}
第一个词是值,另外 3 个词是键
【问题讨论】:
标签: python python-3.x dictionary
您可以在单独的变量中获取第一个单词和其余单词,然后使用 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)
【讨论】: