Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add several values to the same key [closed]

Tags:

ruby

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.

like image 471
user2211703 Avatar asked Nov 01 '13 14:11

user2211703


People also ask

Can you have multiple values for one key?

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.

How do I add more values to a key in Python?

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.

How do you add multiple values to a key in Ruby?

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.

How do you add multiple key value pairs in a dictionary?

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.


3 Answers

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}}
like image 110
Arup Rakshit Avatar answered Oct 04 '22 00:10

Arup Rakshit


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.

like image 40
Some Guy Avatar answered Oct 02 '22 00:10

Some Guy


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} 
like image 22
struthersneil Avatar answered Sep 30 '22 00:09

struthersneil