$ irb irb(main):001:0> h={:foo => "foo_val", :bar => "bar_val"} => {:foo=>"foo_val", :bar=>"bar_val"} irb(main):002:0> puts "Teh %{foo}, teh %{bar} and teh %{quux}" % h.merge({:quux => "quux_val"}) Teh foo_val, teh bar_val and teh quux_val => nil irb(main):003:0> h => {:foo=>"foo_val", :bar=>"bar_val"} irb(main):004:0>
But in the forest girl met Evil Gray Python...
$ python Python 2.6.6 (r266:84292, Oct 1 2010, 13:15:00) [GCC 4.4.4 20100726 (ALT Linux 4.4.4-alt3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> h={"foo": "foo_val", "bar": "bar_val"} >>> print "Teh %(foo)s, teh %(bar)s and teh %(quux)s" % h.update({"quux": "quux_val"}) Traceback (most recent call last): File "", line 1, in TypeError: format requires a mapping
Hate!..
>>> tmp = h.copy().update({"quux": "quux_val"}) >>> tmp
Hate!!.
>>> tmp = h.copy() >>> tmp.update({"quux": "quux_val"}) >>> tmp {'quux': 'quux_val', 'foo': 'foo_val', 'bar': 'bar_val'} >>> print "Teh %(foo)s, teh %(bar)s and teh %(quux)s" % h Teh foo_val, teh bar_val and teh quux_val
Hate!!!
So, the Python ate girl, her mother, her grand-grandmother and all lumbermen...
In [1]: h={"foo": "foo_val", "bar": "bar_val"}
ReplyDeleteIn [2]: print "Teh %(foo)s, teh %(bar)s and teh %(quux)s" % dict(h, **{"quux": "quux_val"})
------> print("Teh %(foo)s, teh %(bar)s and teh %(quux)s" % dict(h, **{"quux": "quux_val"}))
Teh foo_val, teh bar_val and teh quux_val
In [3]: h
Out[3]: {'bar': 'bar_val', 'foo': 'foo_val'}
http://stackoverflow.com/questions/1452995/why-doesnt-a-python-dict-update-return-the-object
ReplyDelete