user7723771
user7723771

Reputation:

Python dictionary of lists, insertion and update with variable key

I want to use a dictionary, with string as key type, and list of strings as value type.

myDict = {}

def addToDictionary(key_str, val_str):
    myDict[key_str].append(val_str)

>>KeyError

My question is, why does this not work? If key_str does not exist in dict, then it should create it and append val_str in the list of values. Seems very straightforward to me, not sure why python is complaining.

Upvotes: 0

Views: 125

Answers (4)

Davidhall
Davidhall

Reputation: 35

The dictionary key hasn't been created yet. You're trying to append and create a key at the same time which doesn't work.

I recommend Iafishers solution it seems best

def KeyGen(key_str, val_str):
    myDict[key_str] = val_str

def AddToDictionary(key_str, val_str):
    myDict[key_str].append(val_str)


KeyGen('testing', [1,2,3])

AddToDictionary('testing', 4)

print myDict

Upvotes: 0

slackmart
slackmart

Reputation: 4924

You are looking for the setdefault method:

myDict.setdefault(key_str, []).append(val_str)

The first time, key_str does not exists in the dictionary, so python will initialize it as a list with one element (val_str), the second time python will use the append method

Here the docs:

setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

Upvotes: 3

Prune
Prune

Reputation: 77837

You've almost answered your own question: if key_str does not exist in myDict, then myDict[key_str] is a keyError, not an empty list. Although you can append to an empty list [ ], you cannot append to a non-existent list.

In short, the dict built-in doesn't read your mind in this case.

Upvotes: 0

iafisher
iafisher

Reputation: 1008

The built-in dictionary class in Python does not have a default value. How could Python know what it should be anyway, since the values can be of any type? What you want is a defaultdict from the collections library.

from collections import defaultdict

# this establishes list as the default factory
myDict = defaultdict(list)

def addToDictionary(key_str, val_str):
    myDict[key_str].append(val_str)

Upvotes: 2

Related Questions