1

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,559
  • 4
  • 28
  • 46

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
  • 65,343
  • 15
  • 148
  • 136
3
>> s = "banana 4 apple 2 orange 4"
>> lst = s.split()
>> dict(zip(lst[::2], lst[1::2]))
ceth
  • 44,198
  • 62
  • 180
  • 289
0

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

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
-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,539
  • 2
  • 27
  • 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