Skip to content

Instantly share code, notes, and snippets.

@edtsech
Created December 23, 2012 18:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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}
@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