wiedhas
wiedhas

Reputation: 35

Python dict key,value returns multiple vaules

I have the following code:

cat_dict =  {
    'ER' : 'ELECTRIC',
    'EL' : 'ELECTRIC',
    "EC" : "ELECTRIC",
    "RM" : "MISC",
    "CP" : "GAS/OIL",
    'P' : 'HYDRO',
    "RP" : "GAS/OIL",
    "OR" : "GAS/OIL",
    "PL" : "MISC",
    "PR" : "GAS/OIL"
}

for key, value in cat_dict.items():
        if cat in key:
            print("CAT: ", value)

I am trying to match a string from the variable "cat", which is a text string, to get the value for the corresponding key but for some reason when the code matches the "P" string, it returns all of the dict values that contain "P" and not just the one match of "HYDRO". Is there a way to match the key:value for just the "P" key and not all P's?

thanks

Upvotes: 0

Views: 58

Answers (3)

Prakriti Shaurya
Prakriti Shaurya

Reputation: 197

"it returns all of the dict values that contain "P" and not just the one match of "HYDRO"."

This is so because you are using "in" operator which means if p is present in the key then print that value. So any key which would be containing p letter the if condition would be executed. Instead you can go for "==" to match two strings.

From the post it is not clear what is cat doing in if condition. Are you trying to match cat with the key, then you can use if cat == key, this is based on the assumption that cat variable holds the letter "P".

Upvotes: 0

Andrew
Andrew

Reputation: 1082

cat_dict =  {
    'ER' : 'ELECTRIC',
    'EL' : 'ELECTRIC',
    "EC" : "ELECTRIC",
    "RM" : "MISC",
    "CP" : "GAS/OIL",
    'P' : 'HYDRO',
    "RP" : "GAS/OIL",
    "OR" : "GAS/OIL",
    "PL" : "MISC",
    "PR" : "GAS/OIL"
}

As I said, it looks like you need == and not in

for key, value in cat_dict.items():
    if cat == key:
        print("CAT: ", value)

More streamlined would be:

print(cat_dict[cat])

Unless you're not certain that the key is there (and a little overengineered, to be honest)

try:
    print(cat_dict[cat])
except KeyError:
    print("key: {} not found".format(cat))

Upvotes: 1

Ben
Ben

Reputation: 454

If i have understood correctly this should work:

 for key, value in cat_dict.items():
            if cat == key:
                print("CAT: ", value)

Note the whole purpose of a dictionary is too convert these. This means this work as well:

cat_dict[cat]

Imagine a dictionary as a list however the index's are what you set them instead of there position.

Upvotes: 1

Related Questions