How do I avoid KeyError when working with dictionaries?

后端 未结 3 1968
说谎
说谎 2020-12-09 17:08

Right now I\'m trying to code an assembler but I keep getting this error:

Traceback (most recent call last):
  File \"/Users/Douglas/Documents/NeWS.py\", line 44,         


        
相关标签:
3条回答
  • 2020-12-09 17:39

    You generally use .get with a default

    get(key[, default])

    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    So when you use get the loop would look like this:

    for item in newS:
        functionField = functionTable.get(item, "00")
        registerField = registerTable.get(item, "00")
        print(functionField + registerField)
    

    which prints:

    1000
    0000
    0000
    

    If you want to do the explicit check if the key is in the dictionary you have to check if the key is in the dictionary (without indexing!).

    For example:

    if item in functionTable:   # checks if "item" is a *key* in the dict "functionTable"
        functionField = functionTable[item]  # store the *value* for the *key* "item"
    else:
        functionField = "00"
    

    But the get method makes the code shorter and faster, so I wouldn't actually use the latter approach. It was just to point out why your code failed.

    0 讨论(0)
  • 2020-12-09 17:43

    You are looking to see if the potential key item exists in in dictionary at item. You simply need to remove the lookup in the test.

    if item in functionTable:
        ...
    

    Though this could even be improved.

    It looks like you try to look up the item, or default to '00'. Python dictionaries has the built in function .get(key, default) to try to get a value, or default to something else.

    Try:

    functionField = functionTable.get(item, '00')
    registerField = registerTable.get(item, '00')
    
    0 讨论(0)
  • 2020-12-09 17:53

    There is no key 'LD' in registerTable. Can put a try except block :

    try:
       a=registerTable[item]
          ...
    except KeyError:
       pass
    
    0 讨论(0)
提交回复
热议问题