0

I'd like to take a string containing tuples that are not well separated and convert them into a dictionary.

s = "banana 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?

Greg
  • 2,429
  • 3
  • 28
  • 43

4 Answers4

5

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'}
>>> 
pyfunc
  • 63,167
  • 15
  • 145
  • 135
3
>> s = "banana 4 apple 2 orange 4"
>> lst = s.split()
>> dict(zip(lst[::2], lst[1::2]))
ceth
  • 42,340
  • 57
  • 170
  • 277
0

Call .split(), get the elements 2 at a time, and pass it to dict().

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
-1

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.

PatrickS
  • 9,569
  • 2
  • 26
  • 31
  • I was thinking you were going to have to split it by character and take the modulo of every third EBCDIC character value. Thanks for clearing that up. – aaronasterling Nov 25 '10 at 06:59
  • not knowing python, i didn't mention any specific method, but the logic remains... split() returns an Array. Not sure what the -1 is for. – PatrickS Nov 25 '10 at 07:59