【问题标题】:Get a dictionary's key by value [duplicate]按值获取字典的键[重复]
【发布时间】:2013-01-02 18:39:56
【问题描述】:

可能重复:
Efficient bidirectional hash table in Python?

我正在开发一个解析 python 代码的 AST 解析器。首先,我通过调用 compile 将 python 代码转换为 AST。
在执行此操作时,我需要确保不会将相同的导入模块编译两次,即使有两次调用导入它也是如此。

目前,我可以检测到这两个调用是等价的:

import modname as mod
import modname as mod

我维护一个字典,将(在这种情况下)mod 映射到modname。我不仅使用它来检测 modname 已经被导入,而且还用于其他一些记账功能。

现在,我无法检测到以下三个调用导入了同一个模块:

import modname as mod
import modname as foo
import modname

我知道我可以通过使用set 来包含modname 并在我第二次编译modname 之前检查这个集合来轻松地绕过这个问题。但是,这需要另一块线性空间。
我可以对字典进行线性传递,以检查是否有任何键映射到 modname 的值,但这违背了使用字典的目的。

因此我的问题是:是否存在一种“双向dict”的数据结构 - 一种将其键映射到值并且其值也可以在 O(1) 时间查找的数据结构?

【问题讨论】:

  • 它不会比两个单向字典占用更少的空间。
  • 你不是已经有一个包含每个模块变量名的结构吗?您将mod 存储在全局还是每个模块的结构中?这就是 Python 的做法; sys.modules 是一个包含所有模块命名空间的映射(包括主脚本的 __main__)。
  • @MartijnPieters:感谢提及sys.modules。这对我的目的有用。我可以检查imported_modules['mod'] in sys.modules。如果您发布您的建议作为答案,我会接受它
  • @inspectorG4dget:我以为你只是在解析,而不是在导入。 :-)

标签: python dictionary hashmap key-value


【解决方案1】:

Python 已经在 sys.modules 中跟踪导入的模块。

每个键都是一个导入的模块名称(而不是导入它的别名),每个值都是具有该模块全局命名空间的实际模块对象:

>>> import sys
>>> import os
>>> 'sys' in sys.modules
True
>>> 'os' in sys.modules
True
>>> sys.modules['sys'].__dict__.keys()
['setrecursionlimit', 'dont_write_bytecode', 'getrefcount', 'path_importer_cache', 'stdout', 'getprofile', '__stdin__', 'version_info', 'exc_clear', 'prefix', 'getfilesystemencoding', 'byteorder', '_clear_type_cache', 'excepthook', 'ps1', 'exc_type', '__excepthook__', 'executable', 'float_info', 'copyright', 'setdlopenflags', 'exec_prefix', 'getdlopenflags', 'getrecursionlimit', 'py3kwarning', 'path_hooks', '__package__', '_current_frames', 'platform', 'maxsize', 'version', 'exit', 'call_tracing', 'callstats', 'flags', 'setcheckinterval', '__doc__', 'api_version', '__plen', 'getdefaultencoding', 'getcheckinterval', 'maxunicode', 'settrace', 'setprofile', 'argv', '__stdout__', 'meta_path', '__name__', 'subversion', 'builtin_module_names', 'stdin', '__stderr__', '__egginsert', 'displayhook', 'ps2', 'gettrace', 'modules', 'warnoptions', 'last_type', 'getsizeof', 'last_traceback', 'maxint', '__displayhook__', '_getframe', 'stderr', 'exc_info', 'path', 'last_value', 'hexversion']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 2014-06-11
    • 2011-12-22
    • 2022-12-05
    相关资源
    最近更新 更多