Python Forum
Comaparing Float Values of Dictionary Against A Float Value & Pick Matching Key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Comaparing Float Values of Dictionary Against A Float Value & Pick Matching Key
#1
Hello Everyone!
Would you help me with the following problem. I have a function that pull data from yahoo finance and return a dictionary of stock names and current stock values - floats. I subsequently use that dictionary in another function, using a float value (pulled from the market as well, e.i getKeysByValues(new_dict, myQuote )) i want to find in my dictionary which key correspond to that value, e.i. myQuote.

I get this
Error:
Traceback (most recent call last): File "C:\Users\...\Desktop\testProcess1.py", line 43, in <module> listOfKeys = getKeysByValues(new_dict, myQuote ) File "C:\Users\...\Desktop\testProcess1.py", line 33, in getKeysByValues if item[1] in listOfValues: TypeError: argument of type 'numpy.float64' is not iterable
error when i use
# get Apple's live quote price
myQuote = live.get_live_price("AAPL")#resulting value here is a float
listOfKeys = getKeysByValues(new_dict, myQuote )#note myQuote has no square bracket
#Iterate over the list of values
for key  in listOfKeys:
But when i use
# get Apple's live quote price
myQuote = live.get_live_price("AAPL")#resulting value here is a float
listOfKeys = getKeysByValues(new_dict, [myQuote] )#myQuote has square bracket
#Iterate over the list of values
for key  in listOfKeys:
    print(key)
the scrpt runs but produces nothing
This is the full script:
#import all modules
from yahoo_fin import stock_info as live
from yahoofinancials import YahooFinancials
import pandas as pd
import numpy as np
#Stock stickers to get data - declared globally
stocks = ['AAPL','MSFT','TSLA']

#Function to extract data
def getStockData():
    #Construct yahoo financials objects for data extraction

            yahoo_financials = YahooFinancials(stocks)
            price = yahoo_financials.get_current_price()
            Open = yahoo_financials.get_open_price()
            High = yahoo_financials.get_daily_high()
            Low = yahoo_financials.get_daily_low()
            perChange = yahoo_financials.get_current_percent_change()
            Volume = yahoo_financials.get_current_volume()
            return(price, Open, High, Low, perChange, Volume)
getChg = lambda: getStockData()[0]
#getChg = getStockData()[4], output:{'AAPL': 208.21, 'MSFT': 140.25, 'TSLA': 227.03}
new_dict = {}
new_dict.update(getChg())#
#dictionary of string and floats - data to compare against
'''
Get a list of keys from dictionary which has value that matches with any value in given list of values
'''
def getKeysByValues(dictOfElements, listOfValues):
    listOfKeys = list()
    listOfItems = dictOfElements.items()
    for item  in listOfItems:
        if item[1] in listOfValues:
            listOfKeys.append(item[0])
    return  listOfKeys
#Now lets use this to find all the keys from dictionary whose values is equal to any value from the list i.e
'''
Get list of keys with any of the given values
'''
#test market value to find match with
# get Apple's live quote price
myQuote = live.get_live_price("AAPL")#resulting value here is a float
listOfKeys = getKeysByValues(new_dict, [myQuote] )
#Iterate over the list of values
for key  in listOfKeys:
    print(key)
Reply
#2
Hello to all!
Thank you having taken the time to stop by and review the submitted the problem, I did manage to solve it by changing
#test market value to find match with
# get Apple's live quote price
myQuote = live.get_live_price("AAPL")#resulting value here is a float
listOfKeys = getKeysByValues(new_dict, [myQuote] )
to
# get Apple's live quote price
yahoo_financials = YahooFinancials('AAPL')
myQuote = yahoo_financials.get_current_price()
listOfKeys = [key  for (key, value) in new_dict.items() if value == myQuote]
Reply
#3
It is worth noting that floats comparison needs additional care when performed.

Look at the following example:
1.3 / 3.9 == 13 / 39
Output:
False
This is due to the finite accuracy of representation float numbers in computer memory.
As of Python 3.5 (PEP-485), you can do such a comparison using math.isclose function.


import math
math.isclose(1.3 / 3.9, 13 / 39)
Output:
True
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching Data - Help - Dictionary manuel174102 1 354 Feb-02-2024, 04:47 PM
Last Post: deanhystad
  need to compare 2 values in a nested dictionary jss 2 797 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Formatting float number output barryjo 2 879 May-04-2023, 02:04 PM
Last Post: barryjo
  Printing specific values out from a dictionary mcoliver88 6 1,317 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  convert string to float in list jacklee26 6 1,814 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  TypeError: 'float' object is not callable #1 isdito2001 1 1,045 Jan-21-2023, 12:43 AM
Last Post: Yoriz
  Write Null values as 0.0 (float) type in csv mg24 3 1,309 Dec-07-2022, 09:04 PM
Last Post: deanhystad
  TypeError: 'float' object is not callable TimofeyKolpakov 3 1,372 Dec-04-2022, 04:58 PM
Last Post: TimofeyKolpakov
  openpyxl convert data to float jacklee26 13 5,713 Nov-19-2022, 11:59 AM
Last Post: deanhystad
  Convert SQLite Fetchone() Result to float for Math Extra 13 3,389 Aug-02-2022, 01:12 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020