How to change all the keys of a hash by a new set of given keys

ruby hash#select
ruby hash map
ruby hash store
ruby hash transform keys
ruby hash rename key
ruby transform hash

How do I change all the keys of a hash by a new set of given keys?

Is there a way to do that elegantly?

Ruby 2.5 has Hash#transform_keys! method. Example using a map of keys

h = {a: 1, b: 2, c: 3}
key_map = {a: 'A', b: 'B', c: 'C'}

h.transform_keys! {|k| key_map[k]}
# => {"A"=>1, "B"=>2, "C"=>3} 

You can also use symbol#toproc shortcut with transform_keys Eg:

h.transform_keys! &:upcase
# => {"A"=>1, "B"=>2, "C"=>3}

How to elegantly rename all keys in a hash in Ruby?, ages = { 'Bruce' => 32, 'Clark' => 28 } mappings = { 'Bruce' => 'Bruce Wayne', '​Clark' => 'Clark Kent' } ages.transform_keys(&mappings.method(:[])) #=> { 'Bruce​  The exact solution would depend on the format that you have the new keys in (or if you can derive the new key from the old key.) Assuming you have a hash h whose keys you want to modify and a hash new_keys that maps the current keys to the new keys you could do:

Assuming you have a Hash which maps old keys to new keys, you could do something like

hsh.transform_keys(&key_map.method(:[]))

Class: Hash (Ruby 2.5.1), This is possible because a hash key in Perl always has to be a string, so if the interpreter Now, having to list all the names of the keys 'manually' all the time, as in our We will see some of these uses in later sections when we start setting up printing out the %words hash: Copy the contents of 'print_array.pl' into a new  The replace (K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. public V replace (K key, V value) Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.

The exact solution would depend on the format that you have the new keys in (or if you can derive the new key from the old key.)

Assuming you have a hash h whose keys you want to modify and a hash new_keys that maps the current keys to the new keys you could do:

h.keys.each do |key|
  h[new_keys[key]] = h[key] # add entry for new key
  k.delete(key)             # remove old key
end

Essential Programming for Linguistics, Trajectory sampling [10, 11] puts particular flow keys in hash tables. Bloom Filters with different resolutions to estimate flow length of any given key. To insert a key c into the table, all the d bits b[h1(c)], b[h2(c)], , b[hd(c)] are set to 1. two aspects: (1) TBF sets a timestamp for each bucket instead of simply setting it to 1  In this article we will discuss different ways to update the value of an existing key in HashMap in Java. Suppose we have a HashMap of words and their frequency count i.e. Now we want to update the value of an existing key “from” to 67. Let’s see how do that, It will update the value V for key K and returns the old value i.e.

Another way to do it is:

hash = {
  'foo' => 1,
  'bar' => 2
}

new_keys = {
  'foo' => 'foozle',
  'bar' => 'barzle'
}

new_keys.values.zip(hash.values_at(*new_keys.keys)).to_h 
# => {"foozle"=>1, "barzle"=>2}

Breaking it down:

new_keys
.values # => ["foozle", "barzle"]
.zip(
  hash.values_at(*new_keys.keys) # => [1, 2]
) # => [["foozle", 1], ["barzle", 2]]
.to_h 
# => {"foozle"=>1, "barzle"=>2}

It's benchmark time...

While I like the simplicity of Jörn's answer, I'm wasn't sure it was as fast as it should be, then I saw selvamani's comment:

require 'fruity'

HASH = {
  'foo' => 1,
  'bar' => 2
}

NEW_KEYS = {
  'foo' => 'foozle',
  'bar' => 'barzle'
}

compare do
  mittag    { HASH.dup.map {|k, v| [NEW_KEYS[k], v] }.to_h }
  ttm       { h = HASH.dup; NEW_KEYS.values.zip(h.values_at(*NEW_KEYS.keys)).to_h }
  selvamani { h = HASH.dup; h.keys.each { |key| h[NEW_KEYS[key]] = h.delete(key)}; h }
end

# >> Running each test 2048 times. Test will take about 1 second.
# >> selvamani is faster than ttm by 39.99999999999999% ± 10.0%
# >> ttm is faster than mittag by 10.000000000000009% ± 10.0%

These are running very close together speed wise, so any will do, but 39% pays off over time so consider that. A couple answers were not included because there are potential flaws where they'd return bad results.

Information Networking Advances in Data Communications and , Set the value of key of hash h. h.clear Pass each key, value of hash h to a block and return true if given block ever returns a value other than false or nil. Return a new hash consisting of entries for which the block returns false of hash h. The Hash::Keys function method returns a LIST containing all keys in a hash. The order of key/value pairs within hash.Keys() and hash.Values() is guaranteed to remain the same as long as no items are added or removed from the hash. Note: If this is an Ordered Hash then the order of the key/value pairs will always be the same. Examples

i assume you want to change the hash keys without changing the values:

hash = {
   "nr"=>"123",
   "name"=>"Herrmann Hofreiter",
   "pferd"=>"010 000 777",
   "land"=>"hight land"
}
header = ["aa", "bb", "cc", "dd"]
new_hash = header.zip(hash.values).to_h

Result:

{
   "aa"=>"123",
   "bb"=>"Herrmann Hofreiter",
   "cc"=>"010 000 777",
   "dd"=>"high land"
}

Ruby Hashes Cheat Sheet, it propagates change between bits, and leads to a more even distribution of 0 and 1 at each position. Consider a set of n keys mapped into an address range of T values. Given a key a and a hashing function h that maps the key into this range, the The worst case for hashing occurs when all the keys hash to the same  Creates a new hash populated with the given objects. Similar to the literal { key => value, In the first form, keys and values occur in pairs, so there must be an even number of arguments.

Database Systems for Advanced Applications '97: Proceedings of the , It consists of building the minimal perfect hash table for the keys and loading the hash table has been built it is not necessary to rebuild it unless the key set changes. The data associated with the keys may change during the table's use, so it whether a given key is or is not in the table, a slightly different approach must  The map holds unique keys. When you invoke put with a key that exists in the map, the object under that key is replaced with the new object. Simply write:count.put('a', 2);The value will override.

Handbook of Research on Modern Systems Analysis and Design , Both will return an array of the keys or values for a given hash. Instead, we can replace that large chunk of code with one simple When it is done executing your block, it will return a new hash with the new set of values. At first, I thought my new keyboard was messed up. So I switched from the brand new one back to my old one. And I still have the same problem. Whwn I hold down the SHIFT and 2 key on my keyboard, it suppossed to make the @ sign right. It doesnt.. instead it makes this " (a paranthesis).

Level Up Your Ruby Skillz: Working With Hashes, In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces. and "drei" ) using three different keys (the strings "one" , "two" , and "​three" ). just like with Arrays, there's a way to set key/value pairs on an existing Hash: Python dictionary method keys() returns a list of all the available keys in the dictionary. Syntax. Following is the syntax for keys() method − dict.keys() Parameters. NA. Return Value. This method returns a list of all the available keys in the dictionary. Example. The following example shows the usage of keys() method.

Comments
  • You are the man! Your hash is totally awesome! Thanks again for this gem! :)
  • It also assumes you have key_map defined as a hash of key/value pairs where the key is the old key and the value is the new key being swapped in.
  • This will remove a value for key when new_keys accidentally happens to return key itself for some key. barbolos's answer to this question: stackoverflow.com/questions/4137824 overcomes this problem.
  • instead of this you can use h.keys.each { |key| h[new_keys[key]] = h.delete(key)}
  • @Selvamani, see my answer, and create an answer from your comment.
  • A moment of self promotion ☺️, but just to leave it here: if anything a bit more complex needed (like select particular keys at the same time or coerce values' types and so on), I put together a tiny lib: github.com/smileart/hash_remapper
  • You take advantage of the fact that order is preserved in hashes (since 2.0 I think) and by assumption (not given in my question) that new keys are also given in the same order as in the initial hash.
  • This breaks if key_map[k] is nil.
  • I think calling merge for each key will be comparatively slow
  • @Josh, you are correct. I re-ran @theTinMan's benchmark with my two methods added and obtained the following results: "selvamani is faster than ttm by 19.99% ± 1.0%; ttm is similar to caryewo (uses each_with_object); caryewo is similar to mittag; mittag is faster than caryred (uses reduce) by 70.0% ± 10.0%".