How can I get a key from a value?
my dict:
countries = {
"Normal UK project" : "1",
"UK Omnibus project" : "1-Omni",
"Nordic project" : ["11","12","13","14"],
"German project" : "21",
"French project" : "31"
}
my semi functioning code:
for k, v in countries.items():
if "1" in v:
print k
expected output:
Normal UK project
actual output:
French project
UK Omnibus project
German project
Normal UK project
How can I fix my code?
解决方案
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