无法根据值检索字典中的键

时间:2019-02-06 05:46:02

标签: python dictionary key

我有一本这样的字典:

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

当我尝试根据以下键访问值时:

print(budget["Jan-16"])

我得到相应的值,即650000打印出来。

但是当我尝试根据以下值获取密钥时:

print(budget.get(650000))

我没有打印。我还尝试过这样获取键值:

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

什么也没打印。

我要去哪里错了?

3 个答案:

答案 0 :(得分:2)

您的代码很好,您只是错过了按照字典中指定的标准检查值。

Fatal Python error: could not acquire lock for <_io.BufferedWriter name='<stdout>'> at interpreter shutdown, possibly due to daemon threads

Thread 0x00007f9fd5ed3700 (most recent call first):
  File "stackover.py", line 27 in ip4write

Thread 0x00007f9fd66d4700 (most recent call first):
  File "stackover.py", line 30 in ip4write

Thread 0x00007f9fd6ed5700 (most recent call first):
  File "/usr/lib/python3.5/subprocess.py", line 1397 in _get_handles
  File "/usr/lib/python3.5/subprocess.py", line 911 in __init__
  File "/usr/lib/python3.5/subprocess.py", line 693 in run
  File "/usr/lib/python3.5/subprocess.py", line 626 in check_output
  File "stackover.py", line 40 in ipve4
  File "stackover.py", line 32 in ip4write

Current thread 0x00007f9fdab47700 (most recent call first):
Aborted (core dumped)

上面的代码输出为:Jan-16

答案 1 :(得分:0)

get(不是值)作为参数,就像[]一样。但是,如果密钥不存在,则可以使用get提供默认值。因此get将无法使用。

您需要对列表的理解进行一些调整才能工作:

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

答案 2 :(得分:0)

反转键,值,然后我们根据值获得键。

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

#output Jan-16