这是一些数据的字典。当我打印它时,它打印在两个不同的列中。我在这里寻找了如何搜索它并找到特定数据的方法,但这对我没有任何意义。如果您能告诉我如何使用日期搜索此信息,然后打印出数据,那将不胜感激。
rainfall = {
'01/08/2014':1.0,
'21/01/2015':0.20,
'22/01/2015':0.10,
'23/01/2015':1.00,
'24/01/2015':0.30,
'25/01/2015':0.40,
'26/01/2015':0.75,
'27/01/2015':0.20,
'28/01/2015':1.00,
'29/01/2015':0.20,
'30/01/2015':0.20,
'31/01/2015':0.30,
}
for k, v in rainfall.items():
print(f'{k:<4} - {v}')
def searching_for_data():
whatdata=input("What date would you like to find (format: DD/MM/YYYY)")
if whatdata in rainfall:
print(find(whatdata))
finddata=input("Would you like to find a specific piece of data?")
if finddata == "Yes":
searching_for_data()
答案 0 :(得分:0)
您需要更改:
if whatdata in rainfall:
print(find(whatdata)
到
if whatdata in rainfall.keys():
print(rainfall[whatdata])
答案 1 :(得分:0)
您可以重写函数以利用dict.__getitem__
或它的语法糖[]
:
def searching_for_data():
whatdata = input("What date would you like to find (format: DD/MM/YYYY)")
if whatdata in rainfall:
print(rainfall[whatdata])
但是您应该养成使用函数return
值的习惯。如果您不希望看到None
,那么如果密钥不存在,上述解决方案也将不起作用。例如,使用dict.get
:
def searching_for_data():
"""Return value if it exists in dictionary, else None"""
whatdata = input("What date would you like to find (format: DD/MM/YYYY)")
return rainfall.get(whatdata)
finddata = input("Would you like to find a specific piece of data?")
if finddata == "Yes":
data = searching_for_data()
print(data)
答案 2 :(得分:0)
您可以在searching_for_data
中使用get函数:
def searching_for_data():
whatdata = input("What date would you like to find (format: DD/MM/YYYY)")
print(rainfall.get(whatdata, 'No data for ' + whatdata))
如果密钥不存在,它允许您定义默认值(或您的情况,提示用户)。
但是,更好的方法是让函数返回值并在顶层执行打印命令:
def searching_for_data():
whatdata = input("What date would you like to find (format: DD/MM/YYYY)")
return rainfall.get(whatdata, 'No data for ' + whatdata)
...
print(searching_for_data())