Renin RK
Renin RK

Reputation: 111

How to handle missing key in dictionary?

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?

Upvotes: 6

Views: 12664

Answers (5)

Amadan
Amadan

Reputation: 198446

get is useful:

{ "exist": True }["notExist"]
# => KeyError
{ "exist": True }.get("notExist")
# => None
{ "exist": True }.get("notExist", 17)
# => 17

for x in testdict:
    print(x["brand"], x.get("year", "N/A"))

Also, in:

"notExist" in { "exist": True }
# => False

for x in testdict:
    if "year" in x:
        print(x["brand"], x["year"])

You can also catch the exception with except, following the EAFP principle (easier to ask for forgiveness than permission):

for x in testdict:
    try:
        print(x["brand"], x["year"])
    except KeyError:
        pass # didn't want to print that anyway

Upvotes: 16

Use this for code.

for val in testdict:
    if len(val) == 3:
        print(val["brand"],val["year"])

Output:

ford 1964
ford 1965
ford 1966
ford 1967
ford 1968
ford 1970
ford 1971
ford 1972
ford 1973
ford 1974

Upvotes: -1

Cam
Cam

Reputation: 1763

You can set a default by using setdefault that will be turned if the key is not found. This works well if you do not have many keys but want to keep referencing the keys you have.

testdict.setdefault('brand', 'Key missing')
testdict.setdefault('year', 'Key missing')

for x in testdict:
    print(x["brand"], x["year"])

If you have a few keys and don't want to keep repeating the same code you could setup a loop to iterate through a list of key names.

list_of_keys = ['brand', 'year']
for key in list_of_key:
    testdict.setdefault(key, 'Key missing')

for x in testdict:
    print(x["brand"], x["year"])

Upvotes: -1

Nikhil Jangir
Nikhil Jangir

Reputation: 51

One of the choice that we have available is to put the code in try-except block. For your case, it should be like

for data in testlist:
    try:
        print(data['brand'],data['year'])
    except KeyError as err:
        # Do something to handle the error

Alternatively, if you just want a particular value to return when the key is not found in the dictionary, you can use the get member method of the dict class as

dictionary.get('Ask for a key',default='Return this in case key not found')

Upvotes: 5

LMSharma
LMSharma

Reputation: 409

I think you can make use of try and except :

for x in testdict:
    try:
        print(x["brand"], x["year"])
    except(KeyError):
        continue

Upvotes: 0

Related Questions