How can I split a string of names and adjacent numbers, such that the numbers are assigned to each adjacent string name?

Viewed 42

I have a list of NBA teams:

teams = ("Los Angeles Clippers","Dallas Mavericks","New York Knicks","Atlanta Hawks")

And the results of some matches:

results = ("Los Angeles Clippers 104 Dallas Mavericks 88,New York Knicks 101 Atlanta Hawks 112")

There are many more names and matches, but for the question I have picked a few.

My question is: how can I split the results scores so that the NBA team names are keys and the scores are values? (I am not looking for code as a solution- just an explanation/description)

Here are my thoughts so far, I know how to add the NBA names as keys in the dictionary, but I am struggling with finding a method to assign the numbers to each team in coding terms. I have got as far as using split() and splitting results at every coma.

I am thinking of then splitting it further, but even if I split each shortened string by name, how can I assign their values next to each of them?

1 Answers

A split wouldn't be very useful, even with a regex, a findall would be much easier,

With a pattern like ([a-zA-Z\s]+) (\d+) for team full name score. I've put the result in a dict by team, but if you have multiple times the same team it'll override as keys are unique, you'll to find another way to store

import re

s = "Los Angeles Clippers 104 Dallas Mavericks 88,New York Knicks 101 Atlanta Hawks 112"
results = re.findall(r"([a-zA-Z\s]+) (\d+)", s)
print(results)
# [('Los Angeles Clippers', '104'), (' Dallas Mavericks', '88'), ('New York Knicks', '101'), (' Atlanta Hawks', '112')]
print(dict(results))
# {'Los Angeles Clippers': '104', ' Dallas Mavericks': '88', 'New York Knicks': '101', ' Atlanta Hawks': '112'}

If you want to group by match

results = re.findall(r"([a-zA-Z\s]+) (\d+) ([a-zA-Z\s]+) (\d+)", s)
# [('Los Angeles Clippers', '104', 'Dallas Mavericks', '88'), 
   ('New York Knicks', '101', 'Atlanta Hawks', '112')]
Related