Search code examples
pythonstringdictionarykeyerror

Key Error while appending data into dictionary of list in Python


I am trying to create a dictionary where the key values are stored in a list like this :

data={
    "key_value":["h1","h2","h3"],
    "key_value2":["h11","h21","h31"],
}

While adding elements to this list of dicts, I am using this function :

data[book_name].append(highlight)

But this gives me a key error KeyError: 'Key_value ' Why is this happening?


Solution

  • As the question stands data.setdefault(book_name, []).append(highlight) can be used. If the key is not present it will create a new key with an empty list as value, else you will get the list for the existing key to which you can append.

    Note : If you have keys that have trailing white spaces this can lead to "unexpected" behavior. eg : data[' key'] vs data['key ']. You can use something like data.setdefault(book_name.strip(), []).append(highlight) to overcome this.

    Suggested Reading :collections.defaultdict