【问题标题】:get python dictionary from string containing key value pairs从包含键值对的字符串中获取python字典
【发布时间】:2012-05-09 23:51:07
【问题描述】:

我有一个格式为:

的python字符串
str = "name: srek age :24 description: blah blah"

有没有办法将它转换成看起来像的字典

{'name': 'srek', 'age': '24', 'description': 'blah blah'}  

其中每个条目都是取自字符串的(键,值)对。我尝试将字符串拆分为列表

str.split()  

然后手动删除:,检查每个标签名称,添加到字典中。这种方法的缺点是:这种方法很讨厌,我必须为每一对手动删除:,如果字符串中有多个单词“值”(例如,blah blah for description),每个单词都会成为列表中不可取的单独条目。是否有任何 Pythonic 获取字典的方法(使用 python 2.7)?

【问题讨论】:

  • 你...删除了之前的问题只是为了再问一次...
  • 是的..那个问题有错误
  • (离题,但是)请不要使用str 作为变量名。这是built-in string type 的名称。
  • @ShawnChin 谢谢..我会记住这一点..

标签: python string dictionary


【解决方案1】:
>>> r = "name: srek age :24 description: blah blah"
>>> import re
>>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
>>> d = dict(regex.findall(r))
>>> d
{'age': '24', 'name': 'srek', 'description': 'blah blah'}

说明:

\b           # Start at a word boundary
(\w+)        # Match and capture a single word (1+ alnum characters)
\s*:\s*      # Match a colon, optionally surrounded by whitespace
([^:]*)      # Match any number of non-colon characters
(?=          # Make sure that we stop when the following can be matched:
 \s+\w+\s*:  #  the next dictionary key
|            # or
 $           #  the end of the string
)            # End of lookahead

【讨论】:

    【解决方案2】:

    没有re:

    r = "name: srek age :24 description: blah blah cat: dog stack:overflow"
    lis=r.split(':')
    dic={}
    try :
     for i,x in enumerate(reversed(lis)):
        i+=1
        slast=lis[-(i+1)]
        slast=slast.split()
        dic[slast[-1]]=x
    
        lis[-(i+1)]=" ".join(slast[:-1])
    except IndexError:pass    
    print(dic)
    
    {'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'}
    

    【讨论】:

      【解决方案3】:

      以原始顺序显示字典的其他 Aswini 程序变体

      import os
      import shutil
      mystr = "name: srek age :24 description: blah blah cat: dog stack:overflow"
      mlist = mystr.split(':')
      dict = {}
      list1 = []
      list2 = []
      try:
       for i,x in enumerate(reversed(mlist)):
          i = i + 1
          slast = mlist[-(i+1)]
          cut = slast.split()
          cut2 = cut[-1]
          list1.insert(i,cut2)
          list2.insert(i,x)
          dict.update({cut2:x})
          mlist[-(i+1)] = " ".join(cut[0:-1])
      except:
       pass   
      
      rlist1 = list1[::-1]
      rlist2= list2[::-1]
      
      print zip(rlist1, rlist2)
      

      输出

      [('name', 'srek'), ('age', '24'), ('description', 'blah blah'), ('cat', 'dog'), ('stack', 'overflow')]

      【讨论】:

        猜你喜欢
        • 2013-07-02
        • 2014-04-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 2022-01-05
        • 2016-12-16
        • 2015-11-12
        • 2016-06-24
        相关资源
        最近更新 更多