Reputation:
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.
Here is the working code which I tried, but want to know if there is any way to optimize the same?
>>> trmode_data = {'continuous': 1, 'fixed': 1}
>>> new = []
>>> for k, v in trmode_data.items():
... if v == 1:
... new.append(k)
>>> if len(new) > 1:
... print "unexpected"
...
unexpected
Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.
Upvotes: 2
Views: 7024
Reputation: 43246
Since you know your dict has exactly 2 items, you can use all
in combination with a comprehension:
if all(val==1 for val in trmode_data.values()):
print('unexpected')
Alternatively, a more generic approach would be to use sum
:
if sum(val==1 for val in trmode_data.values()) > 1:
print('unexpected')
Upvotes: 1
Reputation: 3088
Given your statement:
Whichever key has value 1, that key is to be used further.
It sounds like you want to continue using your dictionary, just w/o the dup key(s) with the value of 1
. (And I'm going to assume you want uniqueness for all values, not just 1
.)
You can achive this by inverting the dictionary. Example:
x = {'a':1, 'b':1, 'c':2}
x_ = {v:k for k,v in x.items()}
x = {v:k for k,v in x_.items()}
print x
Run:
$ python test2.py
{'c': 2, 'b': 1}
BTW, you almost certainty want to use an OrderedDict when reading in from wherever you're reading from, otherwise which key "wins" will be effectively random. But with some sort of ordered dictionary implementation, the last will always win, which is what you specified.
Good luck!
Upvotes: 0