Python 字符串到使用.split()的词典列表

Python 字符串到使用.split()的词典列表,python,python-3.x,dictionary,split,list-comprehension,Python,Python 3.x,Dictionary,Split,List Comprehension,我想拆分telnet查询中给出的数据。我有两个案子: 单一数据: 多数据: 我已尝试使用data=dict(item.split(“”))为data.split(“”)中的项构建单个数据的字典,但我总是遇到以下错误: ValueError: dictionary update sequence element #0 has length 1; 2 is required 我找不到任何好的解决方案来用单一功能构建词典。我期待的是: {'user_name':'tata','user_passwo

我想拆分telnet查询中给出的数据。我有两个案子:

单一数据: 多数据: 我已尝试使用
data=dict(item.split(“”))为data.split(“”)中的项构建单个数据的字典,但我总是遇到以下错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required
我找不到任何好的解决方案来用单一功能构建词典。我期待的是:

{'user_name':'tata','user_password':'12345','user_type':'admin'} 

for multiple results: 
{{'user_name':'tata','user_password':'12345','user_type':'admin'} {'user_name':'toto','user_password':'12345','user_type':'user'}{'user_name':'tonton','user_password':'12345','user_type':'moderator'}} 

您在问题中发布的代码在Python2和Python3上都适用于单个数据:

$ python3
>>> s = "user_name=toto user_password=12345 user_type=admin"
>>> dict(item.split("=") for item in s.split(' '))
{'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}

$ python2
>>> dict(item.split("=") for item in s.split(' '))
{'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}
对于多个数据,您只需将列表理解放在另一个级别:

>>> s = "user_name=toto user_password=12345 user_type=admin|user_name=tata user_password=12345 user_type=user|user_name=tonton user_password=12345 user_type=moderator"
>>> [dict(item.split("=") for item in ss.split()) for ss in s.split('|')]
[{'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}, 
 {'user_password': '12345', 'user_name': 'tata', 'user_type': 'user'},
 {'user_password': '12345', 'user_name': 'tonton', 'user_type': 'moderator'}]
这里的过程是:

  • 在每个管道上拆分管柱
    |
    ,并将其列出
  • 对于此列表中的每个项目,按空格分割(默认分隔符为
    split()
  • 然后,对于每个列表的每个子元素,按相等的
    =
    拆分,并将其用作字典的键值

  • Python的哪个版本(它不能与Python一起工作我认为问题来自telnetlib.read,当我将结果直接放入字符串var中时,这项工作:/
    $ python3
    >>> s = "user_name=toto user_password=12345 user_type=admin"
    >>> dict(item.split("=") for item in s.split(' '))
    {'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}
    
    $ python2
    >>> dict(item.split("=") for item in s.split(' '))
    {'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}
    
    >>> s = "user_name=toto user_password=12345 user_type=admin|user_name=tata user_password=12345 user_type=user|user_name=tonton user_password=12345 user_type=moderator"
    >>> [dict(item.split("=") for item in ss.split()) for ss in s.split('|')]
    [{'user_password': '12345', 'user_name': 'toto', 'user_type': 'admin'}, 
     {'user_password': '12345', 'user_name': 'tata', 'user_type': 'user'},
     {'user_password': '12345', 'user_name': 'tonton', 'user_type': 'moderator'}]