I have a list of dictionary with keys and values. Unfortunately, some keys are not available for some dictionaries. E.g. year 1969 is not available. When I run the code, the output is stuck as there is no "year" key. How can I make the program continue with 1970 and so on?
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"])
I am getting this output:
ford 1964
ford 1965
ford 1966
ford 1967
ford 1968
KeyError Traceback (most recent call last)
<ipython-input-40-8175c2e2026a> in <module>()
1 for x in testdict:
----> 2 print(x["brand"], x["year"])
KeyError: 'year'
How to skip the values which are not present in the dictionary?