-1

please suggest below loop example using defultdict in collections,

i have referred this link for defaultdict

My Question is how to write below loop example in defaultdict in collections to look for key A if not found key B, and return Null even if B is not found.

X = {'A': '1', 'B': '2', 'C': '3'}
Y = X['A'] if "A" in str(X) else X['B'] if "B" in str(X) else ("")

first-priority: if dict has 'A' it will return it's value - 1,
second-priority: if dict has 'B' it will return it's value - 2,
third-priority: if 'A', 'B' are not availble it will return blank - '',

>>> from collections import defaultdict
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>>
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>> ice_cream['Sarah'] = 'Chunky Monkey'
>>> ice_cream['Abdul'] = 'Butter Pecan'
>>> print ice_cream['Sarah']
Chunky Monkey
>>> print ice_cream['Joe']
Vanilla
>>>

required output:

if function is written in defaultdict.. i am expecting something like

function(a, b) --will search a, then b, if both are unavailable return "" (blank)

i want to avoid 'KeyError' and return blank/null if a and b parameters are unavailable in my dict.

please help..

thanks in advance.

Community
  • 1
  • 1
Maria628
  • 224
  • 3
  • 19
  • 1
    Does this answer your question? [Return None if Dictionary key is not available](https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available) – Sayse Nov 29 '19 at 15:16
  • Hi Sayse.. from above link i have found example to return 'Null'/any default value if parameter is not found.. But my requirement is to look for second possibility.. just like if function is written to do so.. function(a, b) --will search a, then b, if both are unavailable return "" (blank) – Maria628 Nov 29 '19 at 15:20
  • Hello! Is there will be only A, B or '' ? Or maybe there will be million of keys to get by priority? – Jefferson Houp Nov 29 '19 at 15:31
  • Only A, then B,, else return Null – Maria628 Dec 01 '19 at 12:39

1 Answers1

0

If you want to avoid 'KeyError' and return blank/null if a and b parameters are unavailable, you can use the try except.

In this specific code, you can use:

a = {"A1": '1', "B": '2', "C": '3'}
try:
    result = a['A'] if "A" in str(a) else a['B'] if "B" in str(a) else ("")

except KeyError:
    result = ''

Let me know if it helps! You can get more info here:

8.3. Handling Exceptions https://docs.python.org/3/tutorial/errors.html

Jesus Fung
  • 76
  • 8
  • thanks for your help.. i am looking if it's possible using collections module in python, instead of using dict.get('a', '') or try..except methods.. – Maria628 Nov 29 '19 at 15:24