Henru Dorsey
Henru Dorsey

Reputation: 15

How to filter a specific, non-constant float out of a list

I'm new to python and I've been trying to write a program to track the total value of my steam inventory. I've been able to retrieve all my skins and the prices, but the issue is isolating the price output from the steam_community_market.market module output, which is a list with a lot of unnecessary information. I haven't been able to find how to filter only specific strings from the lists. An example of the format of the list I'm trying to filter is:

skins_prices = [
    {'Mann Co. Supply Crate Key': {
        'success': True, 
        'lowest_price': '$2.50', 
        'volume': '6,489', 
        'median_price': '$2.45'},
     'AK-47 | Redline (Field-Tested)': {
        'success': True,
        'lowest_price': '$15.00',
        'volume': '749', 
        'median_price': '$14.78'}
    }
]

I haven't gotten to the part of adding the cost together, because first I need to isolate the "lowest price" for each item, how could I do that so I can use that number to calculate the total value/cost (meaning it needs to be a float)? Please tell me if you need more details or have any questions. Anything helps, thanks in advance.

Upvotes: 1

Views: 123

Answers (2)

Sociopath
Sociopath

Reputation: 13426

I think you need:

low_prices = []

# as your list has only 1 component we are using `[0]` and iterating over it
for _, v in skins_prices[0].items():
    low_prices.append(float(v["lowest_price"][1:]))

print(low_prices)

Output:

[2.5, 15.0]

explanation

v["lowest_price"][1:] we are using indexing to ignore the first character from str which is $ so now value will be 2.5 or 15.

On this we are applying float to convert the str into float and appending it to new list which is low_prices

Upvotes: 1

DrSpill
DrSpill

Reputation: 572

This is a problem of nested dictionary as identified in the comment. Here's is a sample code to help out:

key = 'lowest_price'
lowest_prices = {}
for k, v in skins_prices[0].items():
    for k1, v1 in v.items():
        if k1 == key:
            lowest_prices[k] = float(v1[1:])
print(lowest_prices)

output (I have removed the $ and converted to float):

{'Mann Co. Supply Crate Key': 2.5, 'AK-47 | Redline (Field-Tested)': 15.0}

Now you can use the new dictionary to manipulate the values. For example getting the sum total is done as below:

>> sum(list(lowest_prices.values()))
>> 17.5

HTH.

Upvotes: 1

Related Questions