Let's say, for sake of an arbitrary example, that I want to store information about twinned towns. I want to be able to access the data about the twinning by having the names of both towns as keys, but assuming that neither is the 'initial' key. So I'd access the data property like this: twinning_data['derby', 'montreal'] = { 'year': 1986 } or in reverse: twinning_data[ 'montreal', 'derby'] = { 'year': 1986 }.

The best I can come up with is just to concatenate the strings and then try one and then the other way round. Perhaps there is an order independent hash one could use?

  • 1
    If such data structure already exists will depend on the language that you are using. You might want to add a tag for that.
    – null
    Oct 23, 2016 at 16:03
  • 5
    You could just sort the two key items alphabetically before you use your keys for lookups or inserts
    – tiguchi
    Oct 23, 2016 at 16:05
  • @tiguchi - that makes perfect sense, can't believe I didn't think of that!
    – starfish
    Oct 23, 2016 at 16:07

2 Answers 2


You could add them together character by character or perform any other commutative operation, then hash the result.


You could use a normal Map with a Bag<City> or a Set<City> as keys. Maps, Sets, and to a lesser extent Bags are usually available in any decent collections / data structures library.

Here's an example in Ruby:

require 'set'

twinning_data = { Set['derby', 'montreal'] => { year: 1986 } }
twinning_data[Set['montreal', 'derby']]
#=> { :year => 1986 }

Of course, Bags and Sets can technically have an arbitrary number of elements, whereas you want to have exactly 2; ergo, the type is not particularly precise. A more precise type would be some sort of BinaryUndirectedRelation type, which however, probably doesn't readily exist outside of a graph library or the internals of an RDBMS kernel.

  • defining the BinaryUndirectedRelation yourself is fairly easy, just take two elements at construction and store them sorted.
    – Caleth
    Oct 24, 2016 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.