Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get Key by value, dict, python

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?

like image 571
Boosted_d16 Avatar asked Apr 25 '14 14:04

Boosted_d16


People also ask

How do you find the value of the key in a dictionary?

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.

How do you iterate through key-value pairs in Python?

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) .


1 Answers

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"]
like image 172
Serjik Avatar answered Oct 11 '22 15:10

Serjik