Reputation: 183
in my program (that searches for specific keys) i want to implement that it terminates if the key has more than one value. How can i check a key for multiple values?
edit: thanks for clearing up my mistake. It seems my values are lists. In that case how can i check for multiple items in the list that is my value?
Upvotes: 3
Views: 4395
Reputation: 154
Using the len
builtin in python, you can check the length of a list. If the length of the value is more then 1 then there are more then one value in the list.
for key in dictionary: # loop through all the keys
value = dictionary[key] # get value for the key
if len(value) > 1:
break # stop loop if list length is more than 1
Note that this assumes that every value in the dictionary is a list or container.
Upvotes: 2
Reputation: 22544
It is not possible for a dictionary key to have more than one value: either the key is not present in the dictionary, so it has no value, or it is present, and it has one value.
That value may be a tuple, list, dictionary, etc., which contains multiple values, but it is still one value itself. The value may also be None
which can be a marker for no value, but it is still a value.
As @Ulisha's comment said, if you try to assign a new value to a key, the new value will just replace the old value. Again, there can be at most one value for a given key, although there are ways to simulate multiple values by using container objects such a tuple, list, or dict.
If you are looking at a specific item and you want to test if it is a list, you can use
if isinstance(item, list):
This will also catch items that have a type that descends from list, such as a priority queue. If you want to expand that to also detect tuples, dicts, sets, and most other "containers", you can use
if isinstance(item, collections.Container):
For this you will, of course, need to import the collections
module.
Remember that even if the item is a list, it may have no, one, or multiple items.
Upvotes: 1