user1589244
user1589244

Reputation: 445

Python: Split string multiple times; nest the data structure

I'm new to python so apologies for the easy questions. I'm certainly missing something which is getting me confused.

This has something to do with nesting, splitting, and I'm guessing for loops but it's not working out for me.

So here's my original string:

name_scr = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'

I'm trying to create a data structure - dict with the names and scores within it.

So this is what I started with:

    test_scr = { } 
    new_name_scr = [list.split('-') for list in name_scr.split('|')]
# [['alvinone', '90,80,70,50'], ['simonthree', '99,80,70,90'], ['theotwo', '90,90,90,65']]

# this is not  right, and since the output is a list of lists, I cannot split it again 

I get stuck splitting this for the third time at the comma. So then I try the following:

test_scores = {}
for student_string in name_scr.split('|'):
  for student in student_string.split('-'):
    for scores in student.split(','):
      test_scores[student] = [scores]

#but my result for test_scores (below) is wrong
#{'alvinone': ['alvinone'], '99,80,70,90': ['90'], 'theotwo': ['theotwo'], '90,80,70,50': ['50'], '90,90,90,65': ['65'], 'simonthree': ['simonthree']}

I want it to look like this:

  {'alvinone': [99 80 70 50], 'simonthree': [90 80 70 90], 'theotwo': [90 90 90 65]} 

So that when I do this:

print test_scores['simonthree'][2] #it's 70

Please help me here. Keep in mind I'm brand new to python so I don't know too much just yet. Thank you.

Upvotes: 0

Views: 11576

Answers (7)

moooeeeep
moooeeeep

Reputation: 32502

This looks like a perfect use case for PyYAML.

import yaml

# first bring the string into shape
name_scr_yaml = (
    name_scr.replace("|","\n").replace("-",":\n  - ").replace(",","\n  - "))
print name_scr_yaml

# parse string:
print yaml.load(name_scr_yaml)

output is:

alvinone:
  - 90
  - 80
  - 70
  - 50
simonthree:
  - 99
  - 80
  - 70
  - 90
theotwo:
  - 90
  - 90
  - 90
  - 65
{'simonthree': [99, 80, 70, 90], 'theotwo': [90, 90, 90, 65], 'alvinone': [90, 80, 70, 50]}

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

str = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'
a = dict((i.split("-")[0], [x for x in i.split("-")[1].split(',')])  for i in str.split("|"))

Upvotes: 0

hamstergene
hamstergene

Reputation: 24429

>>> splitter = lambda ch: lambda s: s.split(ch)
>>> name_scr = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'
>>> dict( (k,v.split(',')) for k,v in map(splitter('-'), name_scr.split('|')))

{'simonthree': ['99', '80', '70', '90'], 'theotwo': ['90', '90', '90', '65'], 'alvinone': ['90', '80', '70', '50']}

Upvotes: 0

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 50995

A dict can be initialized with a list of two-tuples:

new_name_scr = [x.split('-') for x in name_scr.split('|')]
test_scores = dict((k, v.split(",")) for k, v in new_name_scr)

If you use python2.7+, you can also use dict comprehensions:

test_scores = {k: v.split(",") for k, v in new_name_scr}

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i in s.split('|'):
...   k = i.split('-')
...   d[k[0]] = k[1].split(',')
... 
>>> d['simonthree']
['99', '80', '70', '90']

If you want to have them as int:

>>> for i in s.split('|'):
...   k = i.split('-')
...   d[k[0]] = map(int,k[1].split(','))
... 
>>> d['simonthree']
[99, 80, 70, 90]

Upvotes: 1

avasal
avasal

Reputation: 14854

Your split was correct, all you need to do is iterate over the values and convert it to dict, and to easily access the elements of the dict key, your value should be a list not a string...

Note: while splitting you have used variable name as 'list', which is not a good idea.

check this...

In [2]: str = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'

In [3]: str_list = [l.split('-') for l in str.split('|')]

In [4]: str_list
Out[4]:
[['alvinone', '90,80,70,50'],
 ['simonthree', '99,80,70,90'],
 ['theotwo', '90,90,90,65']]

In [5]: elem_dict = {}

In [6]: for elem in str_list:
   ...:     elem_dict[elem[0]] = [x for x in elem[1].split(',')]
   ...:

In [7]: print elem_dict
{'simonthree': ['99', '80', '70', '90'], 'theotwo': ['90', '90', '90', '65'], 'alvinone': ['90
', '70', '50']}

In [8]: elem_dict['simonthree'][2]
Out[8]: '70'

Upvotes: 2

kheyse
kheyse

Reputation: 1919

name_scr = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'
test_scr = {}

for persinfo in name_scr.split('|'):
    name,scores = persinfo.split('-')
    test_scr[name] = map(int,scores.split(','))

print test_scr

name,scores = [elm0, elm1] unpacks a list into two variables so that name contains list element 0, and scores list element 1.

map(int,['0', '1', '2']) converts a list of strings into a list of integers.

Upvotes: 1

Related Questions