Mokka
Mokka

Reputation: 21

Python- how to convert .txt file (two columns) to dictionary elements?

I want to check min and max of x and y from two columns of .txt file, but I don't know how.

Hi guys :) I did an spectral analysis and I got over 500 lines of frequency and corresponding dB. I wanted to create a dictionary in jupyter notebook that will allow me to check the max and min value of x and y and changes in few spectral analysis. I used this code:

y = {} 

with open('wow.txt', "r") as infile: 
    for line in infile: 
        key, value = line.strip().split(':') 
        y[key] = (value) 
print(y) 

and also

d = {}
with open('wow.txt') as f:
    for line in f:
        key, value = line.strip().split(':')
        d[key] = int(value)

But there is an

ValueError : not enough values to unpack (expected 2, got 1).

I got this values from programme and there are two columns, so what did I do wrong?

Upvotes: 2

Views: 1187

Answers (1)

user8181134
user8181134

Reputation: 486

Somewhere in the text file, there is no ':' character, so it can't split the line. Maybe an empty line somewhere?

Also, for this kind of things, I like to use pandas, a library that has quite some interesting functions for this.

import pandas as pd
df = pd.read_csv(file, delimiter=':', names=['freq', 'db'])
min = df.loc[df['db'].idxmin()]
max = df.loc[df['db'].idxmax()]
print('Minimum at {}Hz with a magnitude of {}dB'.format(min['freq'], min['db']))
print('Maximum at {}Hz with a magnitude of {}dB'.format(max['freq'], max['db']))

Upvotes: 3

Related Questions