ᴀʀᴍᴀɴ
ᴀʀᴍᴀɴ

Reputation: 4528

fill a dictionary without using try except

Suppose I have dictionary and I want to fill that with some keys and values , first dictionary is empty and suppose I need this dictionary for a counter for example count some keys in a string I have this way:

myDic = {}
try :
    myDic[desiredKey] += 1
except KeyError:
    myDic[desiredKey] = 1

Or maybe some times values should be a list and I need to append some values to a list of values I have this way:

myDic = {}
try:
    myDic[desiredKey].append(desiredValue)
except KeyError:
    myDic[desiredKey] = []
    myDic[desiredKey].append(desiredValue)

Is there better alternarive for this works (both of them) that dont uses try except section?

Upvotes: 2

Views: 646

Answers (4)

olofom
olofom

Reputation: 6471

Try this:

myDic = {}
myDic['desiredKey'] = myDic.get('desiredKey', 0) + 1

And similar for your list case:

myDic = {}
myDic['desiredKey'] = myDic.get('desiredKey', []) + [desiredValue]

The .get method for a dict will return the value and default to None instead of throwing an exception. You can also specify the default return value as the second parameter .get(key, default).

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

You can use collections.defaultdict() which allows you to supply a function that will be called each time a missing key is accessed.

And for your first example you can pass the int to it as the missing function which will be evaluated as 0 at first time that it gets accessed.

And for second one you can pass the list.

Example:

from collections import defaultdict 
my_dict = defaultdict(int)

>>> lst = [1,2,2,2,3] 
>>> for i in lst:
...      my_dict[i]+=1
... 
>>> 
>>> my_dict
defaultdict(<type 'int'>, {1: 1, 2: 3, 3: 1})
>>> my_dict = defaultdict(list)
>>> 
>>> for i,j in enumerate(lst):
...     my_dict[j].append(i)
... 
>>> my_dict
defaultdict(<type 'list'>, {1: [0], 2: [1, 2, 3], 3: [4]})

Upvotes: 3

Rockybilly
Rockybilly

Reputation: 4510

I suggest collections.defaultdict

from collections import defaultdict
myDic = defaultdict(int)
myDic[key] = value

as Two-Bit Alchemist adequately put, the best thing about defaultdict is when you need multiple value keys(without having to define the value as a list first). Using d["key"] = value again would just reset the old value, So:

myDic = defaultdict(list)
for key in keys_list:
    myDic[key].append(value)

Upvotes: 3

Will
Will

Reputation: 4469

The best way to do this is with python's excellent in:

myDic = {}
if desiredKey in myDict:
    myDic[desiredKey] += 1
else:
    myDic[desiredKey] = 1

Upvotes: 1

Related Questions