python - 在python中反转字典

标签 python dictionary

我有这本字典

{'jackie chan': ('rush hour', 'rush hour 2'), 
 'crish tucker': ('rush hour', 'rush    hour 2')}

我希望逆字典是

{'rush hour': ('jackie chan', 'crish tucker'), 
 'rush hour 2': ('jackie chan', 'crish tucker')}

我已经得到了反转的功能,但它看起来不像第二个字典

def invert_actor_dict(actor_dict):
    movie_dict = {}
    for key,value in actor_dict.iteritems():

        for actor in value:
            if actor in movie_dict:
                movie_dict[actor].append(key)
            else:
                movie_dict[actor] = (key)
    return movie_dict

最佳答案

您可以使用 collections.defaultdict 轻松完成此操作:

def invert_dict(d):
    inverted_dict = collections.defaultdict(set)
    for actor, movies in d.iteritems():
        for movie in movies:
            inverted_dict.add(actor)
    return inverted_dict

关于python - 在python中反转字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246484/

相关文章:

python - 在 CentOS 上升级到 python 2.7 后如何为 2.7 版本安装 python-devel

haskell - 替换 Data.Map 中的键

ios - Swift - 如何获取字典的最后一个键

python - 使用 Python 2.7 通过 gunicorn 将 bz2 压缩数据作为 utf-8 字符串发送

python - 如何在 API 响应中隐藏密码?

python - 如何将字典作为位置参数而不是关键字参数传递

c++结构图中的值确实以隐藏的方式发生变化

c++ - 无法链接到共享库

python - cx-Freeze 可执行文件无法在另一台计算机上运行

python - 如何获取 Django ImageField 的 url?