I am trying to split on the second,
file = open()
dictionary = {}
for linje in filen:
bites = linje. split()
month = bites[0]
temp = bites[0]
dictionary[month] = temp
print(dictionary)
The file looks like this:
Jan,1,2.7
Jan,2,2.8
Jan,3,0.7
Jan,4,1.8
Jan,5,1.2
...... each day every day of the year.
If I write split(",")
the output becomes this in my dictionary:
{Jan : Jan}.
If I don't split it becomes like this:
{Jan,1,2.7 : Jan,1,2.7}
I want it to be like this:
{Jan,1: 2.7}
CodePudding user response:
You can split from the right and specify how many splits to have:
with open('file_name') as filen:
dictionary = {}
for linje in filen:
month, value = linje.rsplit(',', maxsplit=1)
dictionary[month] = value
print(dictionary)
Sidenote: I suggest opening files as a context manager, i.e. with with
statement.
CodePudding user response:
I would've go with the 'rsplit' solutions above me, but here's a solution with normal split:
file = open()
dictionary = {}
for linje in filen:
digit,temp= linje[4:].split(',')
month = linje[:4] # Months are represented by 3 chars. (4, including the comma)
dictionary[month digit] = temp #concat the digit to the month
print(dictionary)
CodePudding user response:
Split once with rsplit
.
>>> part1, part2 = 'Jan,3,0.7'.rsplit(',', maxsplit=1)
>>> part1
'Jan,3'
>>> part2
'0.7'
CodePudding user response:
file = '''Jan,1,2.7
Jan,2,2.8
Jan,3,0.7
Jan,4,1.8
Jan,5,1.2'''
file = file.split('\n')
keys = []
keysdata = []
for i in range(len(file)):
files = file[i].split(',')
keys.append(f'{files[0]}, {files[1]}')
keysdata.append(float(files[2]))
dictionary = dict(zip(keys, keysdata))
print(dictionary)
Output:
{'Jan, 1': 2.7, 'Jan, 2': 2.8, 'Jan, 3': 0.7, 'Jan, 4': 1.8, 'Jan, 5': 1.2}
CodePudding user response:
Your code can be like this:
file = open()
dictionary = {}
for linje in filen:
bites = linje.rpartition(',')
dictionary[bites[0]] = bites[-1]
print(dictionary)
Example:
st = ["Jan,1,2.7", "Jan,2,2.8", "Jan,3,0.7", "Jan,4,1.8", "Jan,5,1.2"]
{s.rpartition(',')[0] : s.rpartition(',')[-1] for s in st}
Output:
{'Jan,1': '2.7',
'Jan,2': '2.8',
'Jan,3': '0.7',
'Jan,4': '1.8',
'Jan,5': '1.2'}