通过值,字典,Python获取键 [英] get Key by value, dict, python

查看:787
本文介绍了通过值,字典,Python获取键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从值中获取键?

我的字典:

countries = {
        "Normal UK project" : "1",
        "UK Omnibus project" : "1-Omni",
        "Nordic project" : ["11","12","13","14"],
        "German project" : "21",
        "French project" : "31"
        }

我的半功能代码:

for k, v in countries.items():
    if "1" in v:
        print k

预期输出:

Normal UK project

实际输出:

French project
UK Omnibus project
German project
Normal UK project

如何修复我的代码?

推荐答案

问题在于字典中值的类型不同,不仅在这种情况下,使用字典也更加困难.虽然Python允许这样做,但您确实应该考虑统一字典中的类型,例如将它们全部列出.您只需一行代码即可做到:

The problem is that the types of the values in the dictionary are not the same, making it much more difficult to use the dictionary, not only in this scenario. While Python allows this, you really should consider unifying the types in the dictionary, e.g. make them all lists. You can do so in just one line of code:

countries = {key: val if isinstance(val, list) else [val] 
                        for key, val in countries.items()}

现在,每个单个字符串都包装在一个列表中,您现有的代码将正常工作.

Now, each single string is wrapped into a list and your existing code will work correctly.

或者,如果您必须使用当前形式的字典,则可以调整查找功能:

Alternatively, if you have to use the dictionary in it's current form, you can adapt your lookup function:

for k, v in countries.items():
    if "1" == v or isinstance(v, list) and "1" in v:
        print k

这篇关于通过值,字典,Python获取键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆