How to print the Key for particular value in python dictionary if more values are present for one key?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 | dic = {'key1': ["value1", "value2"], 'key2': ["value4","value5"] } "value4" in [x for v in dic.values() for x in v] >> True |
我要为value4而不是true打印密钥
python字典针对按键访问值而不是按相反的顺序进行了优化,因此在这里,您没有比在dict中的所有条目上进行迭代更好的选择:
1 2 3 4 | for key, values in dic.items(): if 'value4' in values: print(key) break |
不确定你要这个,给你-
1 | [k for k, v in dic.iteritems() for i in v if i =="value1"] |
。
如果这解决了问题,请告诉我。
对于独立调用,应该按照@ivaylstrandjev的解决方案迭代
对于重复调用,最好反转字典以保持O(1)查找复杂性。假设您的值不重叠:
1 2 3 4 5 6 7 8 | dic = {'key1': ["value1", "value2"], 'key2': ["value4","value5"]} dic_reverse = {w: k for k, v in dic.items() for w in v} print(dic_reverse) {'value1': 'key1', 'value2': 'key1', 'value4': 'key2', 'value5': 'key2'} |
然后你可以通过
使用列表理解。
前任:
1 2 3 | dic = {'key1': ["value1", "value2"], 'key2': ["value4","value5"] } print( [k for k,v in dic.items() if"value4" in v]) |
输出:
1 | ['key2'] |
。
你可以使用过滤器。
1 2 3 4 | dic = {'key1': ["value1", "value2"], 'key2': ["value4","value5"] } filter(lambda x:"value4" in dic[x], dic) # python 2 list(filter(lambda x:"value4" in dic[x], dic)) # python 3 |
号