Ren*_* RK 1 dictionary python-3.x
我有一个包含键和值的字典列表。不幸的是,某些键对某些词典不可用。例如。1969 年不可用。当我运行代码时,输出卡住了,因为没有“年份”键。我怎样才能让程序继续到 1970 等等?
我是编程新手,不知道如何进行。
testdict = [{"brand": "ford", "model": "Mustang", "year": 1964},
{"brand": "ford", "model": "Mustang", "year": 1965},
{"brand": "ford", "model": "Mustang", "year": 1966},
{"brand": "ford", "model": "Mustang", "year": 1967},
{"brand": "ford", "model": "Mustang", "year": 1968},
{"brand": "ford", "model": "Mustang"},
{"brand": "ford", "model": "Mustang", "year": 1970},
{"brand": "ford", "model": "Mustang", "year": 1971},
{"brand": "ford", "model": "Mustang", "year": 1972},
{"brand": "ford", "model": "Mustang", "year": 1973},
{"brand": "ford", "model": "Mustang", "year": 1974},]
for x in testdict:
print(x["brand"], x["year"])
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
福特 1964
福特 1965
福特 1966
福特 1967
福特 1968
KeyError Traceback(最近一次调用最后一次) in () 1 for x in testdict: ----> 2 print(x["brand"], x["year"])
关键错误:'年'
如何跳过字典中不存在的值?
get 有用:
{ "exist": True }["notExist"]
# => KeyError
{ "exist": True }.get("notExist")
# => Null
{ "exist": True }.get("notExist", 17)
# => 17
for x in testdict:
print(x["brand"], x.get("year", "N/A"))
Run Code Online (Sandbox Code Playgroud)
另外,in:
"notExist" in { "exist": True }
# => False
for x in testdict:
if "year" in x:
print(x["brand"], x["year"])
Run Code Online (Sandbox Code Playgroud)
您还可以使用 捕获异常except,遵循 EAFP 原则(请求宽恕比许可更容易):
for x in testdict:
try:
print(x["brand"], x["year"])
except KeyError:
pass # didn't want to print that anyway
Run Code Online (Sandbox Code Playgroud)
小智 5
我们可用的选择之一是将代码放在 try- except 块中。对于你的情况,它应该是这样的
for data in testlist:
try:
print(data['brand'],data['year'])
except KeyError as err:
# Do something to handle the error
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想在字典中找不到键时返回特定值,则可以使用 dict 类的 get 成员方法:
dictionary.get('Ask for a key',default='Return this in case key not found')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4268 次 |
| 最近记录: |