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?
Return Value from get() get() method returns: the value for the specified key if key is in the dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified.
Iterating over both keys and values Now in case you need to iterate over both keys and values in one go, you can call items() . The method will return a tuple containing the key value pairs in the form (key, value) .
The following code provide another and short version of getting dictionary keys by some value, by using list comprehensions and dic.items():
keys_have_value = [k for k,v in dic.items() if v=="1"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With