Home > other >  Problem of iterating over string and float to find minimum value in dictionary
Problem of iterating over string and float to find minimum value in dictionary

Time:04-28

I need your help on solving iterable and non-iterable values to find the minimum values.

Input:

D1={"Arcadia":{"Month": "January","Atmospheric pressure(hPa)":1013.25},"Xanadu":{"Month:"January","Atmospheric Pressure(hPa)":"No information"},"Atlantis":{"Month":"January","Atmospheric Pressure(hPa):2035.89}}

Output:

The city with the lowest pressure is Arcadia with the Atmospheric Pressure of 1013.25.

This is my code:

 def lowest_pressure(dict1):
  dict_pressure={}  
  exclude = "No information"
  for city,data in dict1.items():
   for value in str(data["Atmospheric Pressure(hPa)"]):
     if value != exclude:
      dict_pressure[city]=data["Atmospheric Pressure(hPa)"]

  low_pressure=min(dict_pressure,key=dict_pressure.get)
  print(f"The city that has the lowest Atmospheric Pressure is {low_pressure} with ${dict_pressure[low_pressure}hPa.") 

lowest_pressure(D1)

If there is a dictionary comprehension I would like to know it too.

Thanks again SO community.

CodePudding user response:

Having edited the dictionary content to what I think it should be, the resulting code should suffice:

D1 = {"Arcadia": {"Month": "January", "Atmospheric Pressure(hPa)": 1013.25},
    "Xanadu": {"Month": "January", "Atmospheric Pressure(hPa)": "No information"},
    "Atlantis": {"Month": "January", "Atmospheric Pressure(hPa)": 2035.89}
    }


t = []

for k, v in D1.items():
    try:
        t.append((float(v['Atmospheric Pressure(hPa)']), k))
    except ValueError:
        pass

if t:
    p, c = min(t)
    print(f'The city with the lowest pressure is {c} with the Atmospheric Pressure of {p:.2f}')
else:
    print('No valid pressure measurements available')

Output:

The city with the lowest pressure is Arcadia with the Atmospheric Pressure of 1013.25

CodePudding user response:

D1={"Arcadia":{"Month": "January","Atmospheric Pressure(hPa)":1013.25},"Xanadu":{"Month":"January","Atmospheric Pressure(hPa)":"No information"},"Atlantis":{"Month":"January","Atmospheric Pressure(hPa)":2035.89}}

country_pressure = {a:D1[a]["Atmospheric Pressure(hPa)"] for a in D1} 

min_pressure = min([a for a in country_pressure.values() if type(a)==int or type(a) ==float])

lowest_pressure_country = None
for k,v in country_pressure.items():
    if v==min_pressure:
        lowest_pressure_country = k
        break

print(f'The city with lowest pressure is {lowest_pressure_country}')

  • Related