Skip to content

Instantly share code, notes, and snippets.

@edtsech
Created December 23, 2012 18:07
Show Gist options
  • Save edtsech/4364933 to your computer and use it in GitHub Desktop.
Save edtsech/4364933 to your computer and use it in GitHub Desktop.
Merge two hashes/dictionaries in Ruby and Python.
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h3 = h1.merge(h2)
h3 #=> {"a"=>100, "b"=>254, "c"=>300}
h1 #=> { "a" => 100, "b" => 200 }
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
@jjb
Copy link

jjb commented Oct 28, 2016

you may be amused to learn that this is the first hit on google for

python update ruby merge

@dbercht
Copy link

dbercht commented Sep 19, 2017

And this one

ruby merge dictionaries

@xoen
Copy link

xoen commented Jul 6, 2018

An important distinction is that in Python when using x.update() it will update x, e.g. changes the instance you're calling it on. In Ruby this is not the case, call x.merge(y) doesn't change x, instead the method returns a new Hash.

Not trolling here :trollface: but to be honest I prefer Ruby's behaviour as it doesn't have a side effect. Bear in mind you can achieve Python's behaviour (update the instance) by calling #merge! instead of #merge.

@xoen
Copy link

xoen commented Jul 10, 2018

Today I discovered that there is a nice way to "merge" dictionaries in Python:

{ **x, **y }

This is very useful because you can get assign this result to a new dictionary or update the existing one:

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = {**x, **y}  # This creates a new dictionary and assign to z. Similar to Ruby's `z = x.merge(y)`
x = {**x, **y}  # This updates `x` with the result of the merge. Similar to Ruby's `x.merge!(y)`

@andyhd
Copy link

andyhd commented Jul 11, 2018

That's only valid syntax in Python 3.5. In Python 2, you could do

x = {'a': 1}
y = {'b': 2}
z = dict(x, **y)

@r4vi
Copy link

r4vi commented Jul 11, 2018

x = {**x, **y} # not the same as
x.update(y)  
# because a new dict is constructed and assigned to x
x = {'x': 'xxxx'}
y = {'y': 'yyyy'}
id(x), id(y)
(140215338406176, 140215338368816)
x = {**x, **y}; x
{'x': 'xxxx', 'y': 'yyyy'}
id(x)
140215338405960

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment