Krithika Raghavendran
Krithika Raghavendran

Reputation: 457

Can't retrieve key in a dictionary based on value

I have a dictionary that looks like this:

budget = {'Jan-16': '650000', 'Feb-16': '-1100387', 'Mar-16': '-174946', 'Apr-16': '757143', 'May-16': '445709'}

When I try to access the value based on key such as:

print(budget["Jan-16"])

I get the corresponding value i.e. 650000 printed.

But when I try to get the key based on value such as:

print(budget.get(650000))

I get None printed. I have also tried to get the key value like so:

print([for k, v in budget.items() if v == 650000]) 

and nothing gets printed.

Where am I going wrong?

Upvotes: 0

Views: 75

Answers (3)

Vikas Viki
Vikas Viki

Reputation: 56

Your Code is fine, you just missed to check the value as a stirng as specified in the dictionary.

budget = {'Jan-16': '650000', 'Feb-16': '-1100387', 'Mar-16': '-174946', 'Apr- 
16': '757143', 'May-16': '445709'}
for k, v in budget.items():
    if v == '650000':
        print(k)

The Output of the above code is : Jan-16

Upvotes: 2

vinodsesetti
vinodsesetti

Reputation: 418

reversing key,values and then we get the key based on values.

print ({v:k for k, v in budget.items()}.get('650000'))

#output Jan-16

Upvotes: 0

busybear
busybear

Reputation: 10590

get takes keys (not values) as arguments--just like [] does. However, with get you can provide a default value if the key doesn't exist. So get won't work for your use.

Your list comprehension just needs to be tweaked a bit to work:

[k for k, v in budget.items() if v == '650000']

Upvotes: 0

Related Questions