Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
2.78/5 (3 votes)
See more:
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
Posted
Comments
Sergey Alexandrovich Kryukov 8-May-14 3:01am    
Why? why?!
—SA
Member 9566937 8-May-14 3:08am    
I give first preference to pen so I change position to 0 and save in database using single dictionary
Sergey Alexandrovich Kryukov 8-May-14 3:14am    
Not clear. Dictionaries are not about "preference", they are used to find a value by key with O(1) time complexity.
I answered.
—SA

1 solution

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
 
Share this answer
 
v2
Comments
Volynsky Alex 8-May-14 3:57am    
Nice!
Sergey Alexandrovich Kryukov 8-May-14 8:52am    
Thank you, Alex.
—SA
Volynsky Alex 8-May-14 8:53am    
You're welcome Sergey Alexandrovich

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900