0

I have a random function that assigns values only to some of the dict keys, but i cant run my code with others undefined. Is there a way to set a default value if the variable isnt defined?

One way i thought about solving this is assigning each key in dict None value and then update the dict with defined variables. Is that the only way?

defined_variable = 'value'

dictionary = {
'key1': defined_variable,
'key2': undefined_varible # gives me NameError
}

print(dictionary)



#  --- maybe something like this?

defined_variable = 'value'

dictionary = {
'key1': defined_variable,
try:
    'key2': undefined_varible
except NameError:
    # code
}

print(dictionary) 
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    Does this answer your question? [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – pppery Jun 12 '20 at 23:00
  • 1
    Maybe use `defaultdict` – Barmar Jun 12 '20 at 23:00
  • What a fun to cause error and then trying to handle it. – Olvin Roght Jun 12 '20 at 23:00
  • 1
    Conceptionally [EAFP](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python) is not so strange in python, right @OlvinRoght ? Of course this is a rather deterministic error... – David Wierichs Jun 12 '20 at 23:09
  • @DavidWierichs, take a look on code. Author using undefined variable and trying to handle exception which it causes. It's like shoot in your leg an complain that it hurts. – Olvin Roght Jun 12 '20 at 23:10
  • Yes, that's what I meant by deterministic, maybe not the best choice of word, sorry. Maybe in a more complex application it would not be clear whether `undefined_vari(a)ble` is actually defined, and then you don't know whether you hit the foot ;-) I agree on the solution with @pppery btw. – David Wierichs Jun 12 '20 at 23:13

1 Answers1

0

I believe I can help you here. We should rely on the defaultdict from the Collections module.

from collections import defaultdict
dictionary  = defaultdict(str) # If you want a default value to be a number, use 'int'.
dictionary['key1'] = 'defined_variable'

This returns:

defaultdict(str, {'key1': 'defined_variable'})

We then execute (without assigning anything):

dictionary['key2']

And you will get a empty string assigned to 'key2' - i.e., empty string becomes a default value.

defaultdict(str, {'key1': 'defined_variable', 'key2': ''})
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dev
  • 665
  • 1
  • 4
  • 12