【问题标题】:Pythonic way of making a dict from a string从字符串制作字典的 Pythonic 方式
【发布时间】:2021-03-04 13:26:45
【问题描述】:

我有这段代码,它接受字符串输出并将其转换为字典,它可以工作,但我想知道是否有更好的方法,特别是在拆分字符串方面,因为它有点笨重。

代码

string = "Position = 1009.82391102873, Height = 8.3161791611302, Weight = 0.650591370984836"

def string_to_dict(string): 
    mydict = {}
    temp_list = list(string.split(","))
    big_list = []
    for item in temp_list:
        item_split_list = list(item.split(" = "))
        big_list.append(item_split_list)
        mydict[item_split_list[0]] = item_split_list[1]     
    return mydict 

mydict = string_to_dict(string)
print(mydict)
print(type(mydict))

退货

{'Position': '1009.82391102873', ' Height': '8.3161791611302', ' Weight': '0.650591370984836'}
<class 'dict'>

【问题讨论】:

  • 你被,分割,然后被=分割,你strip()最后你应该有键和值。基本上你什么都做,除了脱衣舞。

标签: python list dictionary split


【解决方案1】:

你可以在一行中完成:

dct = dict(s.split('=') for s in string.replace(' ', '').split(','))

但如果您希望值为float:

dct = {k: float(v) for s in string.replace(' ', '').split(',') for k, v in [s.split('=')]}

结果:

>>> dct
{'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}

【讨论】:

  • 您的代码似乎可以工作,但从 Python 之禅的意义上说,这只是工作的一部分。它不容易阅读,可读性很重要。
  • 如果键或值中有空格,这将不起作用。
  • @KlausD.:您认为哪一部分不透明或难以阅读?对我来说似乎非常易读和简单。
【解决方案2】:
temp_list = list(string.split(","))

new_dict = {temp_list[i].split("=")[0].strip():temp_list[i].split("=")[1].strip()}

这有点奇怪,但它很有效,而且更“pythonic”

【讨论】:

    【解决方案3】:

    连接可能会有所帮助。

    [输入]

    keys = [x.split('=')[0].strip() for x in string.split(',')]
    arg = [x.split('=')[1].strip() for x in string.split(',')]
    new_dict = dict(zip(keys, arg))
    

    [输出]

    new_dict
    {'Position ': ' 1009.82391102873',
     ' Height ': ' 8.3161791611302',
     ' Weight ': ' 0.650591370984836'}
    

    【讨论】:

      【解决方案4】:

      单行:

      dict(kv.replace(" ", "").split("=") for kv in string.split(","))
      

      给了

      {'Position': '1009.82391102873',
       'Height': '8.3161791611302',
       'Weight': '0.650591370984836'}
      

      该行首先将原始字符串按, 拆分,将字符串分成"key = value" 的列表。这些字符串中的空格被删除以获得类似"key=value" 的字符串,然后这些字符串被= 拆分以获得类似[["key1", "value1"], ["key2", "value2"]] 的列表。因为这些列表的长度都是 2,所以我们可以将其传递给 dict 以构造字典。

      作为@VishalSingh cmets,如果键或值有空格,这将不起作用。

      【讨论】:

      • 如果键或值中有空格,这将不起作用。
      • @VishalSingh - 当然,但 OP 的字符串没有空格
      【解决方案5】:

      您可以使用字典理解来创建一个新字典。

      your_dict = {
          pair.split("=")[0].strip(): pair.split("=")[1].strip()
          for pair in string.split(",")
      }

      【讨论】:

        【解决方案6】:

        为了锻炼的美感,我能想到的最短形式是:

        >>> eval(f"dict({string})")
        {'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}
        

        或者没有 f-strings

        >>> eval("dict({})".format(string))
        {'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}
        

        但是,鉴于阅读困难,我不会说这是最好的 Python 方式

        【讨论】:

        • 它很漂亮,如果代码仅供我阅读,我会使用它,谢谢 MarcoP。
        猜你喜欢
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 2022-11-18
        • 2013-09-02
        • 2018-08-10
        • 2023-03-11
        • 2013-09-06
        相关资源
        最近更新 更多