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.