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} |
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
That's only valid syntax in Python 3.5. In Python 2, you could do