How can you convert a list of poorly formed data pairs into a dict?
I'd like to take a string containing tuples that are not well separated and convert them into a dictionary.
s = "ba开发者_StackOverflownana 4 apple 2 orange 4"
d = {'banana':'4', 'apple':'2', 'orange':'4'}
I'm running into a problem because the space is used to separate the values as well as the pairs. What's the right trick?
Simplistic but serves the solution here:
Use split()
>>> s = "banana 4 apple 2 orange 4"
>>> s.split()
['banana', '4', 'apple', '2', 'orange', '4']
>>>
Group them ( Some error checks required here)
>>> k = [(x[t], x[t+1]) for t in range(0, len(x) -1, 2)]
>>> k
[('banana', '4'), ('apple', '2'), ('orange', '4')]
>>>
Create a dictionary out of it
>>> dict(k)
{'orange': '4', 'banana': '4', 'apple': '2'}
>>>
>> s = "banana 4 apple 2 orange 4"
>> lst = s.split()
>> dict(zip(lst[::2], lst[1::2]))
Call .split()
, get the elements 2 at a time, and pass it to dict()
.
I don't know python but it should be possible to convert the string into an array , then iterate thru the array to create a dictionary by alternating name & value.
精彩评论