有没有更好的方式存储一个双语字典比存储其反向分离? [英] Is there a better way to store a twoway dictionary than storing its inverse separate?

查看:130
本文介绍了有没有更好的方式存储一个双语字典比存储其反向分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个一对一的字典(= bijection)生成àla

 为key,value在someGenerator中:
myDict [key] = value

反向查找字典可以通过添加

  invDict [value] = key 

循环。但这是一个Pythonic的方式吗?我应该写一个类Bijection(dict),它另外管理这个倒排的字典,并提供第二个查找功能?还是这样一个结构(或类似的一个)已经存在?

解决方案

reverseict 函数,它将采用一个dict并返回相反的映射,如果我知道它是一对一的(抛出异常,看到相同的值两次)或值列表的键,如果不是。这样一来,每次我想要反向查找时,并不需要在同一时间构建两个dict,所以我可以正常地创建我的dicts,只需调用通用的 reverseict 功能到底。



但是,似乎 bidict reverseict 函数似乎是他的双手的运算符)。


Given a one-to-one dictionary (=bijection) generated à la

for key, value in someGenerator:
     myDict[key] = value

an inverse lookup dictionary can be trivially created by adding

    invDict[value] = key

to the for loop. But is this a Pythonic way? Should I instead write a class Bijection(dict) which manages this inverted dictionary in addition and provides a second lookup function? Or does such a structure (or a similar one) already exist?

解决方案

What I've done in the past is created a reversedict function, which would take a dict and return the opposite mapping, either values to keys if I knew it was one-to-one (throwing exceptions on seeing the same value twice), or values to lists of keys if it wasn't. That way, instead of having to construct two dicts at the same time each time I wanted the inverse look-up, I could create my dicts as normal and just call the generic reversedict function at the end.

However, it seems that the bidict solution that Jon mentioned in the comments is probably the better one. (My reversedict function seems to be his bidict's ~ operator).

这篇关于有没有更好的方式存储一个双语字典比存储其反向分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆