Reputation: 74
I would like split data given from telnet query. I got two case:
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
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
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:
|
and make a list of itsplit()
)=
and use it as a key-value for the dictionaryUpvotes: 1