Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary using input from a file

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.

like image 879
Lee Yaan Avatar asked Mar 07 '23 15:03

Lee Yaan


1 Answers

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

  • Read file with appropriate delimiter and name columns.
  • Split by comma and map each element to integer type via list comprehension.
  • Create series indexed by Club and use .to_dict() to output dictionary.
like image 98
jpp Avatar answered Mar 19 '23 07:03

jpp