Home > Blockchain >  Find a key associated with a value using indexing
Find a key associated with a value using indexing

Time:11-20

I have a dictionary of where the keys are cities and the values are lists of rent values. What I wanted to do is return the lowest average rent and the city associated with it. I am very new to python so I was hoping for a solution that avoided import and rather for loops or indexing.

{'Houston': [1400.0, 860.0, 1498.0], 'Los Angeles': [1560.0, 1350.0, 600.0, 940.0], 'New York': [873.0, 11510.0, 1021.0]}

CodePudding user response:

Finding the average for each:

data = {
  'Houston': [1400.0, 860.0, 1498.0], 
  'Los Angeles': [1560.0, 1350.0, 600.0, 940.0], 
  'New York': [873.0, 11510.0, 1021.0]
}


for city, rents in data.items():
    print(f"{city}: Avg rent: ${sum(rents) / len(rents) : 0.2f}")

We can get these values in a list with a comprehension.

[sum(rents) / len(rents) for city, rents in data.items()]

We can convert this list comprehension to a generator expression and pass it to min to find the smallest average rent.

min(sum(rents) / len(rents) for city, rents in data.items())

Now, we know the minimum average rent. We need to find any cities where that is the average rent. We can use a dictionary comprehension for that.

>>> def avg(vals): return sum(vals) / len(vals)
... 
>>> min_avg = min(avg(rents) for _, rents in data.items())
>>> {k: data[k] for k in data.keys() if avg(data[k]) == min_avg}
{'Los Angeles': [1560.0, 1350.0, 600.0, 940.0]}
>>> 

CodePudding user response:

You could use dict.keys() to return a list of the cities in your dictionary and then use for i in range(len(dict.keys())) to loop through your dictionary and find the average at each stop and store both i (the city) and the average and go from there.

  • Related