Key Error: "city"

Ben Finney ben+python at benfinney.id.au
Sat Sep 9 02:20:00 EDT 2017


V Vishwanathan <viradha at hotmail.com> writes:

> alert = "Today's forecast for {city}: The temperature will range from{low_temperature} "" to ""{high_temperature}{temperature_unit}Conditions will be {weather_conditions}".format(city,low_temperature,high_temperature,temperature_unit,weather_conditions)
> print(alert)

The ‘str.format’ method accepts positional arguments and keyword
arguments.

When you want to refer to the arguments by name, the method must know
their names; that means passing them to the method as keyword arguments.

> Traceback (most recent call last):
>   File "D:\python exercises\uda format1.py", line 6, in <module>
>     alert = "Today's forecast for {city}: The temperature will range from{low_temperature} "" to ""{high_temperature}{temperature_unit}Conditions will be {weather_conditions}".format(city,low_temperature,high_temperature,temperature_unit,weather_conditions)
> KeyError: 'city'

Your format string refers to keys (names) that are not found in the
dictionary of keyword arguments — because you passed no keyword
arguments.

Instead, give a keyword argument for each name you want to refer to in
the format string.

-- 
 \          “There's a certain part of the contented majority who love |
  `\            anybody who is worth a billion dollars.” —John Kenneth |
_o__)                                            Galbraith, 1992-05-23 |
Ben Finney




More information about the Python-list mailing list