0

I am having the following dict

a= {"b":"2", "c":"3","e":"5"}

and I am using if statement to find the presence of keys in dict as follows

if ("c" or "s") in a:
    print a['s']

I am getting error if the key s is not available. But I have a['c']

My question is how can I get the value of the particular key in the print statement. i.e the print statement should be independent of the keys in if statement.

Rakahbarp
  • 23
  • 3
  • 1
    `any(x in a for x in ("c", "s"))` ? – Goodies Dec 01 '16 at 08:34
  • 1
    All your statement does is evaluate to `if "c" in a`. The "s" is never checked because that's the nature of the `or` statement. Because "c" is a True-like value (a non-empty string), it is evaluated. – Goodies Dec 01 '16 at 08:35
  • `'c' or 's'` is evaluated first; since any non-empty string is considered *true*, only `'c'` is returned from that expression. So Python next tests `'c' in a`. Use `'c' in a or 's' in a`, or use use a set intersection with `a.viewkeys() & {'c', 's'}` or `not {'c', 's'}.isdisjoint(a)`. – Martijn Pieters Dec 01 '16 at 08:36
  • @MartijnPieters, I have used `a.viewkeys() & {'c', 's'}` and I get output as `set(['c'])` and now I am not clear, how to get the value of respective key from dictionary – Rakahbarp Dec 01 '16 at 10:18
  • If you want the value of *one* of those keys, then use `dict.get()`; so `a.get('c', a.get('s'))` would get you the value of either `c` or `s`, or `None` if neither exists. – Martijn Pieters Dec 01 '16 at 11:17
  • Got it.. Thanks much @MartijnPieters – Prabhakar Dec 01 '16 at 11:21

0 Answers0