【问题标题】:How to map a String as a dict in python?如何在python中将字符串映射为字典?
【发布时间】:2021-10-11 02:57:11
【问题描述】:

我在 python 中有一个字符串:-

Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10 10:15:22

如何将其映射到:-

{'apple':105.2  ,'Goog':101,'TSLA':200,Time:2021:10:10 10:15:22 } 

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    这将引发错误。字典值不能有多个用冒号分隔的数值(如Time 键所示)。我认为您的意思是:

    dictionary = {'apple': 105.2, 'Goog': 101, 'TSLA': 200, 'Time': '2021:10:10:23'}
    

    您可以使用以下代码:

    dictionary = {}
    
    string = 'Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23'
    
    # Split the string by commas and store the items in a list
    enter code herestring_items = string.split(",") # ['Stock Price', 'apple:105.2', 'Goog:101', 'TSLA:200', 'Time:2021:10:10:23']
         
    # Remove the first item (i.e., "Stock Price")
    string_items.pop(0)
    
    for item in string_item:
        dictionary[item.split(":", 1)[0]] = item.split(":", 1)[1]
    

    注意:这仍会将数字保留为字符串文字。

    【讨论】:

      【解决方案2】:

      这里是:

      str = "Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23"
      
      s = str.split(',')[1:]
      stocks = {}
      for tickr in s:
          new_dict = tickr.split(':')
          stocks[new_dict[0]] = new_dict[1]
      

      【讨论】:

        【解决方案3】:

        用逗号分割字符串,跳过第一部分。然后在字典构造函数中使用这些字符串,方法是在第一个冒号上拆分它们:

        s = 'Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23'
        d = dict(kv.split(':',1) for kv in s.split(',')[1:])
        
        print(d)
        {'apple': '105.2', 'Goog': '101', 'TSLA': '200', 'Time': '2021:10:10:23'}
        

        您必须执行额外的步骤才能将“时间”值转换为实际的日期时间对象。

        【讨论】:

          猜你喜欢
          • 2011-01-18
          • 2021-05-09
          • 2023-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多