簡體   English   中英

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

[英]String to list of dictionaries using .split()

我想從telnet查詢中分割數據。 我有兩種情況:

單一數據:

user_name=toto user_password=12345 user_type=admin`

多種數據:

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

我試圖為data = dict(item.split("=") for item in data.split(' '))使用data = dict(item.split("=") for item in 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'}} 

您在問題中發布的代碼在單個數據的Python 2和Python 3上都可以正常運行:

$ 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'}]

這里的過程是:

  1. 在每個管道上分割字符串| 並列出清單
  2. 對於此列表的每個項目,按空格分隔( split()默認分隔符)
  3. 然后,對於每個列表的每個子元素,將其除以等於=並將其用作字典的鍵值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM