Created
December 23, 2012 18:07
-
-
Save edtsech/4364933 to your computer and use it in GitHub Desktop.
Merge two hashes/dictionaries in Ruby and Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> x = {'a':1, 'b': 2} | |
>>> y = {'b':10, 'c': 11} | |
>>> z = x.update(y) | |
>>> print z | |
None | |
>>> x | |
{'a': 1, 'b': 10, 'c': 11} |
And this one
ruby merge dictionaries
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 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
.
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)`
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)
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
you may be amused to learn that this is the first hit on google for