Search code examples
pythonloopsdictionaryiterable

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


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.


Solution

  • 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