I have a file with the following format:
Barcelona 2015,2016,2017
Real Madrid 2010
Napoli 2007,2009
Bayern Munich 2008,2009,2010,2011,2012,2013
I want to save this to a dictionary having the team and next a list with the numbers. How can I make this? I have some difficulties in splitting because some teams have bigger names.
This is the Pandas solution, assuming 4-space delimiter.
import pandas as pd
from io import StringIO
mystr = StringIO("""Barcelona 2015,2016,2017
Real Madrid 2010
Napoli 2007,2009
Bayern Munich 2008,2009,2010,2011,2012,2013""")
df = pd.read_csv(mystr, delimiter=' ', header=None, names=['Club', 'Years'])
df['Years'] = [list(map(int, x)) for x in df['Years'].str.split(',')]
d = df.set_index('Club')['Years'].to_dict()
Result
{'Barcelona': [2015, 2016, 2017],
'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013],
'Napoli': [2007, 2009],
'Real Madrid': [2010]}
Explanation
.to_dict()
to output dictionary.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With