Creating a dictionary using file input

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 in a dictionary having a command, and the following list with numbers. How can i do this? I have some difficulties in separation because some teams have big names.

+4
source share
5 answers

As requested, a pure-python solution that

  • non-regular expression
  • more than one liner
  • very readable

data = {}
with open('file.txt') as f:
    for line in f:
        city, dates = line.rstrip().rsplit(None, 1)
        data[city] = [int(d) for d in dates.split(',')]

data
{
    "Barcelona": [
        2015,
        2016,
        2017
    ],
    "Real Madrid": [
        2010
    ],
    "Napoli": [
        2007,
        2009
    ],
    "Bayern Munich": [
        2008,
        2009,
        2010,
        2011,
        2012,
        2013
    ]
}
+1
source

This is a Pandas solution involving a 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 the file with the appropriate separator and name columns.
  • Separate by comma and map each element to an integer type through list comprehension.
  • , , .to_dict() .
+4

re , :

import re
final_d = {a:map(int, b.split(',')) for a, b in map(lambda x:re.split('\s+(?=\d)', x.strip('\n')), open('filename.txt').readlines())}

:

{'Real Madrid': [2010], 'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013], 'Barcelona': [2015, 2016, 2017], 'Napoli': [2007, 2009]}
+1

,

file = open('file_name')
d = {}
for line in file.readlines():
   try:
       key, value = line.replace('\n','').split('\t') ##if your sep == '\t'
   except ValueError:
       pass ### if line is empty
   else: ### if all is ok
       d[key] = value
print(d)
+1
source

It works, I don’t know if this is what you want.

file=open("info.txt", "r")
lines1=file.readlines()
lines=[]
for i in lines1:
    lines.append(i.split("   "))
output={}
for i in lines:
    key=i[0]
    exec("item=("+i[1]+")")
    output[key]=item
0
source

Source: https://habr.com/ru/post/1695063/


All Articles