我怎样才能换掉我的词典 [英] How Can I Swap My Dictionary

查看:84
本文介绍了我怎样才能换掉我的词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何交换字典值和键



ex:



在我的字典中有数据库记录。数据库表有2列项目和位置如

box 0

pen 1

car 2



现在我在数据网格中只显示基于位置的字典

box

pen

car



现在我需要交换字典项目并改变位置



pen 0

box 1

car 2

How to swap dictionary values & key

ex:

In my dictionary have database records. Database table have 2 columns items and position like
box 0
pen 1
car 2

Now I displayed dictionary in data grid only items based on position
box
pen
car

now I need to swap dictionary items and also change position

pen 0
box 1
car 2

推荐答案

快速而肮脏的答案是:创建另一个字典并从原始字典中填充它遍历所有键值对源字典并使用键作为值和值作为键。



但是,它似乎是一个坏主意,因为这种算法在一般情况下不起作用:键当然是唯一的,值不是,因此在倒置字典中添加键值对通常会导致异常:键重复。如果你对它做了一些事情,比如说,排除重复,你将得到不完整的倒置字典,元素少于原始字典。



所以,如果你真的需要这样的东西(再次,为什么?以及你对唯一性的要求是什么),一致的方法是这样的:封装两个具有相同键和值的字典,但是在一个类字典类的键值对中反转顺序。您将能够向此类实例添加一对,其中一对元素用作一个字典中的键,另一个元素用作另一个字典中的值。当然,两个结果字典都不会在键中没有重复,也不会在值中重复。很简单。



-SA
Quick and dirty answer would be: create another dictionary and populate it from the original one traversing all key-value pairs of the source dictionary and using keys as values and values as keys.

However, it may appear to be a bad idea, because such algorithm won't work in general case: keys are of course unique and values are not, so adding key-values pairs in "inverted" dictionary will generally result in exception: key duplicates. If you do something about it, say, exclude duplicates, you will end up with incomplete "inverted" dictionary, with less elements than the original one.

So, if you really need something like that (again, why? and what would be your requirements on uniqueness), the consistent method would be this: encapsulate two dictionaries with same keys and values but inverted order in key-value pairs in one dictionary-like class. You will be able to add a pair to this class instance, with one element of the pair serving as a key in one dictionary and a value in another one. Of course, both resulting dictionaries won't have no duplicates in keys and no duplicates in values. Quite simply.

—SA


这篇关于我怎样才能换掉我的词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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