简体   繁体   English

字典-检查键是否有多个值

[英]Dictionaries - Check key for multiple values

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? 在那种情况下,我该如何检查列表中是否有我所值的多个项目?

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. 该值也可以是None ,可以作为无值的标记,但它仍然是一个值。

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. 正如@Ulisha的评论所说,如果您尝试为键分配新值,则新值将替换旧值。 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. 为此,您当然需要导入collections模块。

Remember that even if the item is a list, it may have no, one, or multiple items. 请记住,即使该项目是一个列表,也可能没有,一个或多个项目。

Using the len builtin in python, you can check the length of a list. 使用python内置的len ,您可以检查列表的长度。 If the length of the value is more then 1 then there are more then one value in the list. 如果值的长度大于1,则列表中的值大于1。

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. 请注意,这假定字典中的每个值都是列表或容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM