【问题标题】:how to convert string to Dictionary by first word is value and 3 more words is keys如何将字符串转换为字典,第一个单词是值,另外 3 个单词是键
【发布时间】:2021-09-16 18:51:48
【问题描述】:

例如,我想将字符串转换为字典 我的字符串是"Man I Je Ich" 所以字典结果是

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

第一个词是值,另外 3 个词是键

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python python-3.x dictionary


【解决方案1】:

您可以在单独的变量中获取第一个单词和其余单词,然后使用 dict 推导式创建 dict

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

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

【讨论】:

    【解决方案2】:

    这个工作文件:

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

    【讨论】:

    • 非常感谢
    【解决方案3】:

    试试这个哑巴..

    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)  
    

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 2016-12-21
      • 2019-04-07
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多