Gecko
Gecko

Reputation: 74

String to list of dictionaries using .split()

I would like split data given from telnet query. I got two case:

Single data:

user_name=toto user_password=12345 user_type=admin`

Multiple data:

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

I have tried to build my dictionary for single data with data = dict(item.split("=") for item in data.split(' ')), but I always get this error:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I don't find any good solution to build my dictionary with single feature. What I am expecting is:

{'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'}} 

Upvotes: 0

Views: 1920

Answers (1)

Maxime Lorant
Maxime Lorant

Reputation: 36161

The code you have posted in your question works fine on both Python 2 and Python 3 for single data:

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

For multiple data, you just need to put another level of list comprehension:

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

The process here is:

  1. Split the string at each pipe | and make a list of it
  2. For each item of this list, split by space (default separator of split())
  3. Then for each sub-element of each list, split by equal = and use it as a key-value for the dictionary

Upvotes: 1

Related Questions