【问题标题】:Accessing a Dictionary [closed]访问字典[关闭]
【发布时间】:2015-11-29 05:36:38
【问题描述】:

我需要编写一个函数get_value(dictionary, key),它返回给定字典中给定键的值。

我的代码

dictionary = {'Sunday':0, 'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4, 'Friday':5, 'Saturday':6}  
get_value = input("Provide key") 
for day in dictionary:
    if dictionary[day]['key'] == get_value:
        print (day)

【问题讨论】:

  • 已批准。你可以继续。
  • 我在您的代码中没有看到任何get_value 函数,您尝试了什么?
  • get_value = input("Provide key") get_value(dict,key) 的函数?

标签: python dictionary


【解决方案1】:

要访问字典中的值,您只需使用dictionary[key],因此您只需在函数中返回该值即可。

【讨论】:

    【解决方案2】:

    试试这样的:

    dictionary = {'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6}  
    
    get_value = input("Provide key: ") 
    
    if get_value in dictionary:
        print(dictionary[get_value])
    else:
        print('Key not found!')
    

    【讨论】:

    • print(dictionary.get(get_value, 'Key not found!'))
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多