【问题标题】:How to convert a line having string into dictionary using python?如何使用python将具有字符串的行转换为字典?
【发布时间】:2016-02-04 08:43:27
【问题描述】:

我有一行:

Name:sample   Location:(xyz)

我想把它转换成字典如下:

{'Name':'sample','Location':'(xyz)'}

我想使用 python 脚本来做到这一点。所以,请建议我如何使这成为可能。我正在开发的平台是 linux。

【问题讨论】:

    标签: file dictionary python-2.6


    【解决方案1】:
     # First split at whitespaces ==> ['Name:sample', 'Location:(xyz)']
     # Next split each item at ':' and convert them into list of tuples
     #    ==>[('Name', 'sample'), ('Location', '(xyz)')]
     # Convert the list of tuples to dictionary
    
    sample_string       = "Name:sample   Location:(xyz)"
    
    split_sample_string = sample_string.split()
    
    tuple_string        = [tuple(item.split(":")) for item in split_sample_string]
    
    final_dictionary = dict(tuple_string)
    
    print final_dictionary
    # final_dictionary = {'Name': 'sample', 'Location': '(xyz)'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2013-03-13
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多