Exchange keys with values and vice-versa from an associative array can be a very common problem. Let's how we can solve it:
This native function will do the job on the fly!
<?php
var_dump( array_flip( array('a', 'b', 'c') ) );
If you use underscore.js, you have the invert method.
_.invert([1, 2]);
We can easily build a function to emulate the PHP array_flip function
function array_flip(trans)
{
var key, tmp_ar = {};
for ( key in trans )
{
if ( trans.hasOwnProperty( key ) )
{
tmp_ar[trans[key]] = key;
}
}
return tmp_ar;
}
There's a good way to create an associative array and exchange values with Python using the dictionary structure.
a = dict()
a['one'] = 1
a['two'] = 2
res = dict((v,k) for k,v in a.iteritems())
print res