如何将键作为参数

How to put a key as an argument

我是 试图将一个键作为这个函数的参数,我只是不知道该怎么做:

city = {"Paris": 183, "Lyon": 220, "Marseille": 222 ,"Surfers Paradise": 475}

def plane_ride_cost(city): 
      for key, value in city():
         return value


print(plane_ride_cost("Marseille"))

我得到了这个答案:

Traceback (most recent call last):
  File "C:/Users/vion1/ele/Audric/TP 9.py", line 25, in <module>
    print(plane_ride_cost("Marseille"))
  File "C:/Users/vion1/ele/Audric/TP 9.py", line 9, in plane_ride_cost
    for key, value in city():
TypeError: 'str' object is not callable

感谢您的帮助!

您使用与函数参数相同的变量名覆盖了全局 city 变量。将您的全局字典重命名为 cities 之类的名称,然后引用它来避免冲突和不必要的行为。

函数 plane_ride_cost() 内的 city 没有括号,因为它们用于函数,字符串不是函数 :)

def plane_ride_cost(city): 
      for key, value in city.items(): #removed parentheses (was city())
         return value
city = {"Paris": 183, "Lyon": 220, "Marseille": 222 ,"Surfers Paradise": 475}

##define the parameter as the key
def plane_ride_cost(cityName): 
      return city[cityName] #return the value from dictionary using the key passed


print(plane_ride_cost("Marseille"))  #returns 222