how can I add several values to the same key? Something like this:
x = {}
x["k1"] = nil
x["k1"] << {"a" => "a"}
x["k1"] << {"b" => "b"}
well, this doesn't work like with array.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.
Instead of {:key => value1,value2} , think {:key => [{:subkey_1 => value_1},{:subkey_2 => value_2}]} -- that's what you can do in Ruby, at least.
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
You can do as below :
For Array
as value to the key of a Hash
:
h = Hash.new{|hsh,key| hsh[key] = [] }
h['k1'].push 'a'
h['k1'].push 'b'
p h # >> {"k1"=>["a", "b"]}
For Hash
as value to the key of a Hash
:
h = Hash.new{|hsh,key| hsh[key] = {} }
h['k1'].store 'a',1
h['k1'].store 'b',1
p h # >> {"k1"=>{"a"=>1, "b"=>1}}
Depends on just what you're trying to accomplish here. If you want a hash of arrays, that's easy enough:
x = {}
x['k1'] = Array.new
x['k1'] << 'a'
x['k1'] << 'b'
or if you want nested hashes, simple enough as well
x = {}
x['k1'] = {}
x['k1']['a'] = 'a'
x['k1']['b'] = 'b'
the values in a hash are just objects. They can be arrays, other hashes, or whatever else you might want.
So, you want the value of key 'k1' to be a hash, and you want to add key/value pairs to that hash. You can do it like this:
2.0.0-p195 :111 > x = {}
=> {}
2.0.0-p195 :112 > x['k1'] = { 'a' => '1' }
=> {"a"=>"1"}
2.0.0-p195 :117 > x['k1'].merge!({ 'b' => '2' })
=> {"a"=>"1", "b"=>"2"}
Or, you can do it like this:
2.0.0-p195 :119 > x['k1']['c'] = 3
=> 3
2.0.0-p195 :120 > x['k1']
=> {"a"=>"1", "b"=>"2", "c"=>3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With