Home > Software design >  How to retrieve key value of dictionary with a specific key value, within a list of dictionaries
How to retrieve key value of dictionary with a specific key value, within a list of dictionaries

Time:06-26

I would appreciate if someone would be kind enough to help me figure this out.

In this example I have a list of dictionaries where each dictionary contains various parameters about a stock 'Symbol'. I'm trying to retrieve the 'Quantity' of stocks in the list for a given 'Symbol'. If the 'Symbol' doesn't exist in the list it should return 0.

p = [
    {'AveragePrice': '8.5334167347', 'AssetType': 'STOCK', 'Quantity': '124', 'Symbol': 'FNGU'}, 
    {'AveragePrice': '6.5334167347', 'AssetType': 'STOCK', 'Quantity': '100', 'Symbol': 'SPY'}, 
    {'AveragePrice': '7.5215053838', 'AssetType': 'STOCK', 'Quantity': '69', 'Symbol': 'LABU'}
    ]

def getposition(symbol):
    for d in p:
        if d["Symbol"] == symbol:
            q = int(d["Quantity"])
        else:
            q = 0
    return q

print("LABU", getposition("LABU"))
print("FNGU", getposition("FNGU"))
print("SPY", getposition("SPY"))
print("AAPL", getposition("AAPL"))

But I keep getting false results:

LABU 69
FNGU 0
AAPL 0
SPY 0

What would be the correct way to scan through the list to get the correct results?

Thanks!

CodePudding user response:

For your function, your else statement caused the q to reset as it was in a for loop. By instead keeping the q outside of the scope of the for loop, setting it equal to 0 and then dropping the else statement, we are able to achieve the desired result:

p = [
    {'AveragePrice': '8.5334167347', 'AssetType': 'STOCK', 'Quantity': '124', 'Symbol': 'FNGU'}, 
    {'AveragePrice': '6.5334167347', 'AssetType': 'STOCK', 'Quantity': '100', 'Symbol': 'SPY'}, 
    {'AveragePrice': '7.5215053838', 'AssetType': 'STOCK', 'Quantity': '69', 'Symbol': 'LABU'}
    ]

def getposition(symbol):
  q = 0
  for d in p:
    if d['Symbol'] == symbol:
      q = int(d["Quantity"])
  return q

print("FNGU", getposition("FNGU"))
print("SPY", getposition("SPY"))
print("LABU", getposition("LABU"))
print("AAPL", getposition("AAPL"))

Hope this helps!

CodePudding user response:

You need to stop after finding the correct value, otherwise you always overwrite the found value if the required symbol is not in the last dict in the list (also, maybe raise an exception or use a better sentinel value, as a stock might actually be worth 0):

def getposition(symbol):
    for d in p:
        if d["Symbol"] == symbol:
            return int(d["Quantity"])
     return 0

However, this is O(n). Since we already assume symbol is unique, it would be better to use it as a key in a dict of dicts:

p = {
    'FNGU': {
        'AveragePrice': '8.5334167347',
        'AssetType': 'STOCK',
        'Quantity': '124',
        'Symbol': 'FNGU'
    },
    'SPY': {
        'AveragePrice': '6.5334167347',
        'AssetType': 'STOCK',
        'Quantity': '100',
        'Symbol': 'SPY'
    },
    'LABU': {
        'AveragePrice': '7.5215053838',
        'AssetType': 'STOCK',
        'Quantity': '69',
        'Symbol': 'LABU'
    }
}    

Now we get direct O(1) access and don't need to iterate over the entire data:

print(int(p['SPY']['Quantity']))
100
  • Related