【问题标题】:Issue in creating a creating a dictionary from a string从字符串创建字典时的问题
【发布时间】:2020-08-14 10:38:39
【问题描述】:

我有以下字符串。我正在将其转换为字典,但我正在检索的输出不是预期的输出。

result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'

mydict = dict((k.strip(), v.strip()) for k,v in 
          (item.split('and') for item in result.split(',')))
print(mydict)
output is: {'Thomas got 99': 'James got 95', 'Gerrard got 84': 'Tim got 21'}

我希望预期的输出如下所示

 output is:{'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}

谢谢

【问题讨论】:

    标签: python python-3.x string dictionary


    【解决方案1】:

    使用 zip() 函数从两个列表中创建字典

    import re
    result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'
    key = re.findall('[A-Z]+[a-z]+',result)
    value = re.findall(r'\d+',result)
    print(dict(zip(key,value)))
    #{'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}
    

    【讨论】:

      【解决方案2】:

      使用正则表达式。

      例如:

      import re
      
      result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'
      print(dict(re.findall(r"(\w+) got (\d+)", result)))
      

      输出:

      {'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}
      

      【讨论】:

        【解决方案3】:

        尝试改变 and 而不是 got,不要有这么多的“and”,只需使用逗号就可以了

        result = ' Thomas got 99, James got 95, Gerrard got 84, Tim got 21'
        mydict = dict((k.strip(), v.strip()) for k,v in 
              (item.split('got') for item in result.split(',')))
        print(mydict)
        

        在我的 IDE 中运行它,结果就是您想要的,希望对您有所帮助

        【讨论】:

          猜你喜欢
          • 2021-12-01
          • 2014-04-19
          • 2016-12-02
          • 2011-07-06
          • 1970-01-01
          • 1970-01-01
          • 2016-03-23
          • 1970-01-01
          相关资源
          最近更新 更多