title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
578,444
<p>Check out <a href="http://groups.google.com/group/python-dbase">http://groups.google.com/group/python-dbase</a></p> <p>It currently supports dBase III and Visual Foxpro 6.0 db files... not sure if the file layout change in VFP 9 or not...</p>
5
2009-02-23T17:08:19Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
10,254,842
<p>I was able to read a DBF file (with associated BAK, CDX, FBT, TBK files**) using the dbf package from PyPI <a href="http://pypi.python.org/pypi/dbf">http://pypi.python.org/pypi/dbf</a> . I am new to python and know nothing about DBF files, but it worked easily to read a DBF file from my girlfriend's business (created with a music store POS application called AIMsi). </p> <p>After installing the dbf package (I used aptitude and installed dbf version 0.88 I think), the following python code worked:</p> <pre><code>from dbf import * test = Table("testfile.dbf") for record in test: print record x = raw_input("") # to pause between showing records </code></pre> <p>That's all I know for now, but hopefully it's a useful start for someone else who finds this question!</p> <blockquote> <p>April 21, 2012 SJK Edit: Per Ethan Furman's comment, I should point out that I actually don't know <em>which</em> of the data files were necessary, besides the DBF file. The first time I ran the script, with only the DBF available, it complained of a missing support file. So, I just copied over the BAK, CDX, FPT (not FBT as I said before edit), TBK files and then it worked. </p> </blockquote>
8
2012-04-20T23:33:30Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
38,730,628
<p>It's 2016 now and I had to fiddle with the dbf package to get it to work. Here is a python3 version to just export a dbf file to a csv</p> <pre><code>import dbf d=dbf.Table('mydbf.dbf') d.open() dbf.export(d, filename='mydf_exported.csv', format='csv', header=True) </code></pre> <p>I had some unicode error at first, but got around that by turning off memos.</p> <pre><code>import dbf d=dbf.Table('mydbf.dbf', ignore_memos=True) d.open() dbf.export(d, filename='mydf_exported.csv', format='csv', header=True) </code></pre>
4
2016-08-02T21:18:47Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
38,254
<p>Alternative constructors are the classic example.</p>
22
2008-09-01T18:27:27Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
38,276
<p>Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.</p> <p>If you have a class <code>MyClass</code>, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a <code>classmethod</code>. Then it'll be available to subclasses.</p>
142
2008-09-01T18:45:56Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
38,287
<p>Honestly? I've never found a use for staticmethod or classmethod. I've yet to see an operation that can't be done using a global function or an instance method.</p> <p>It would be different if python used private and protected members more like Java does. In Java, I need a static method to be able to access an instance's private members to do stuff. In Python, that's rarely necessary.</p> <p>Usually, I see people using staticmethods and classmethods when all they really need to do is use python's module-level namespaces better.</p>
4
2008-09-01T18:54:29Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
38,303
<p>Factory methods (alternative constructors) are indeed a classic example of class methods.</p> <p>Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.</p> <p>As an example, in the excellent <a href="http://pypi.python.org/pypi/Unipath/0.2.1">unipath</a> module:</p> <h2>Current directory</h2> <ul> <li><code>Path.cwd()</code> <ul> <li>Return the actual current directory; e.g., <code>Path("/tmp/my_temp_dir")</code>. This is a class method.</li> </ul></li> <li><code>.chdir()</code> <ul> <li>Make self the current directory.</li> </ul></li> </ul> <p>As the current directory is process wide, the <code>cwd</code> method has no particular instance with which it should be associated. However, changing the <code>cwd</code> to the directory of a given <code>Path</code> instance should indeed be an instance method.</p> <p>Hmmm... as <code>Path.cwd()</code> does indeed return a <code>Path</code> instance, I guess it could be considered to be a factory method...</p>
53
2008-09-01T19:08:25Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
2,311,096
<p>I used to work with PHP and recently I was asking myself, whats going on with this classmethod? Python manual is very technical and very short in words so it wont help with understanding that feature. I was googling and googling and I found answer -> <a href="http://code.anjanesh.net/2007/12/python-classmethods.html">http://code.anjanesh.net/2007/12/python-classmethods.html</a>.</p> <p>If you are lazy to click it. My explanation is shorter and below. :)</p> <p>in PHP (maybe not all of you know PHP, but this language is so straight forward that everybody should understand what I'm talking about) we have static variables like this:</p> <pre><code> class A { static protected $inner_var = null; static public function echoInnerVar() { echo self::$inner_var."\n"; } static public function setInnerVar($v) { self::$inner_var = $v; } } class B extends A { } A::setInnerVar(10); B::setInnerVar(20); A::echoInnerVar(); B::echoInnerVar(); </code></pre> <p>The output will be in both cases 20.</p> <p>However in python we can add @classmethod decorator and thus it is possible to have output 10 and 20 respectively. Example:</p> <pre><code> class A(object): inner_var = 0 @classmethod def setInnerVar(cls, value): cls.inner_var = value @classmethod def echoInnerVar(cls): print cls.inner_var class B(A): pass A.setInnerVar(10) B.setInnerVar(20) A.echoInnerVar() B.echoInnerVar() </code></pre> <p>Smart, ain't?</p>
5
2010-02-22T13:27:12Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
2,807,576
<p>I recently wanted a very light-weight logging class that would output varying amounts of output depending on the logging level that could be programmatically set. But I didn't want to instantiate the class every time I wanted to output a debugging message or error or warning. But I also wanted to encapsulate the functioning of this logging facility and make it reusable without the declaration of any globals.</p> <p>So I used class variables and the <code>@classmethod</code> decorator to achieve this.</p> <p>With my simple Logging class, I could do the following:</p> <pre><code>Logger._level = Logger.DEBUG </code></pre> <p>Then, in my code, if I wanted to spit out a bunch of debugging information, I simply had to code</p> <pre><code>Logger.debug( "this is some annoying message I only want to see while debugging" ) </code></pre> <p>Errors could be out put with </p> <pre><code>Logger.error( "Wow, something really awful happened." ) </code></pre> <p>In the "production" environment, I can specify </p> <pre><code>Logger._level = Logger.ERROR </code></pre> <p>and now, only the error message will be output. The debug message will not be printed.</p> <p>Here's my class:</p> <pre><code>class Logger : ''' Handles logging of debugging and error messages. ''' DEBUG = 5 INFO = 4 WARN = 3 ERROR = 2 FATAL = 1 _level = DEBUG def __init__( self ) : Logger._level = Logger.DEBUG @classmethod def isLevel( cls, level ) : return cls._level &gt;= level @classmethod def debug( cls, message ) : if cls.isLevel( Logger.DEBUG ) : print "DEBUG: " + message @classmethod def info( cls, message ) : if cls.isLevel( Logger.INFO ) : print "INFO : " + message @classmethod def warn( cls, message ) : if cls.isLevel( Logger.WARN ) : print "WARN : " + message @classmethod def error( cls, message ) : if cls.isLevel( Logger.ERROR ) : print "ERROR: " + message @classmethod def fatal( cls, message ) : if cls.isLevel( Logger.FATAL ) : print "FATAL: " + message </code></pre> <p>And some code that tests it just a bit:</p> <pre><code>def logAll() : Logger.debug( "This is a Debug message." ) Logger.info ( "This is a Info message." ) Logger.warn ( "This is a Warn message." ) Logger.error( "This is a Error message." ) Logger.fatal( "This is a Fatal message." ) if __name__ == '__main__' : print "Should see all DEBUG and higher" Logger._level = Logger.DEBUG logAll() print "Should see all ERROR and higher" Logger._level = Logger.ERROR logAll() </code></pre>
23
2010-05-11T01:48:33Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
3,504,391
<p>Class methods provide a "semantic sugar" (don't know if this term is widely used) - or "semantic convenience".</p> <p>Example: you got a set of classes representing objects. You might want to have the class method "all" or "find" to write "User.all()" ou "User.find(firstname='Guido')". That could be done using module level functions of course...</p>
3
2010-08-17T15:53:14Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
3,521,920
<p>Think about it this way: normal methods are useful to hide the details of dispatch: you can type <code>myobj.foo()</code> without worrying about whether the <code>foo()</code> method is implemented by the <code>myobj</code> object's class or one of its parent classes. Class methods are exactly analogous to this, but with the class object instead: they let you call <code>MyClass.foo()</code> without having to worry about whether <code>foo()</code> is implemented specially by <code>MyClass</code> because it needed its own specialized version, or whether it is letting its parent class handle the call.</p> <p>Class methods are essential when you are doing set-up or computation that <em>precedes</em> the creation of an actual instance, because until the instance exists you obviously cannot use the instance as the dispatch point for your method calls. A good example can be viewed in the SQLAlchemy source code; take a look at the <code>dbapi()</code> class method at the following link:</p> <p><a href="https://github.com/zzzeek/sqlalchemy/blob/ab6946769742602e40fb9ed9dde5f642885d1906/lib/sqlalchemy/dialects/mssql/pymssql.py#L47" rel="nofollow">https://github.com/zzzeek/sqlalchemy/blob/ab6946769742602e40fb9ed9dde5f642885d1906/lib/sqlalchemy/dialects/mssql/pymssql.py#L47</a></p> <p>You can see that the <code>dbapi()</code> method, which a database backend uses to import the vendor-specific database library it needs on-demand, is a class method because it needs to run <em>before</em> instances of a particular database connection start getting created — but that it cannot be a simple function or static function, because they want it to be able to call other, supporting methods that might similarly need to be written more specifically in subclasses than in their parent class. And if you dispatch to a function or static class, then you "forget" and lose the knowledge about which class is doing the initializing.</p>
37
2010-08-19T12:51:27Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
6,001,200
<p>I think the most clear answer is <strong>AmanKow's</strong> one. It boils down to how u want to organize your code. You can write everything as module level functions which are wrapped in the namespace of the module i.e</p> <pre><code>module.py (file 1) --------- def f1() : pass def f2() : pass def f3() : pass usage.py (file 2) -------- from module import * f1() f2() f3() def f4():pass def f5():pass usage1.py (file 3) ------------------- from usage import f4,f5 f4() f5() </code></pre> <p>The above procedural code is not well organized, as you can see after only 3 modules it gets confusing, what is each method do ? You can use long descriptive names for functions(like in java) but still your code gets unmanageable very quick.</p> <p>The object oriented way is to break down your code into manageable blocks i.e Classes &amp; objects and functions can be associated with objects instances or with classes. </p> <p>With class functions you gain another level of division in your code compared with module level functions. So you can group related functions within a class to make them more specific to a task that you assigned to that class. For example you can create a file utility class :</p> <pre><code>class FileUtil (): def copy(source,dest):pass def move(source,dest):pass def copyDir(source,dest):pass def moveDir(source,dest):pass //usage FileUtil.copy("1.txt","2.txt") FileUtil.moveDir("dir1","dir2") </code></pre> <p>This way is more flexible and more maintainable, you group functions together and its more obvious to what each function do. Also you prevent name conflicts, for example the function copy may exist in another imported module(for example network copy) that you use in your code, so when you use the full name FileUtil.copy() you remove the problem and both copy functions can be used side by side.</p>
8
2011-05-14T10:24:32Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
9,867,663
<p>When a user logs in on my website, a User() object is instantiated from the username and password.</p> <p>If I need a user object without the user being there to log in (e.g. an admin user might want to delete another users account, so i need to instantiate that user and call its delete method):</p> <p>I have class methods to grab the user object.</p> <pre><code>class User(): #lots of code #... # more code @classmethod def get_by_username(cls, username): return cls.query(cls.username == username).get() @classmethod def get_by_auth_id(cls, auth_id): return cls.query(cls.auth_id == auth_id).get() </code></pre>
6
2012-03-26T06:36:52Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
12,312,026
<p>This is an interesting topic. My take on it is that python classmethod operates like a singleton rather than a factory (which returns a produced an instance of a class). The reason it is a singleton is that there is a common object that is produced (the dictionary) but only once for the class but shared by all instances.</p> <p>To illustrate this here is an example. Note that all instances have a reference to the single dictionary. This is not Factory pattern as I understand it. This is probably very unique to python.</p> <pre><code>class M(): @classmethod def m(cls, arg): print "arg was", getattr(cls, "arg" , None), cls.arg = arg print "arg is" , cls.arg M.m(1) # prints arg was None arg is 1 M.m(2) # prints arg was 1 arg is 2 m1 = M() m2 = M() m1.m(3) # prints arg was 2 arg is 3 m2.m(4) # prints arg was 3 arg is 4 &lt;&lt; this breaks the factory pattern theory. M.m(5) # prints arg was 4 arg is 5 </code></pre>
2
2012-09-07T05:06:16Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
14,042,417
<p>It allows you to write generic class methods that you can use with any compatible class.</p> <p>For example:</p> <pre><code> @classmethod def get_name(cls): print cls.name class C: name = "tester" C.get_name = get_name #call it: C.get_name() </code></pre> <p>if you dont use @classmethod you can do it with self keyword but it needs an instance of Class:</p> <pre><code> def get_name(self): print self.name class C: name = "tester" C.get_name = get_name #call it: C().get_name() #&lt;-note the its an instance of class C </code></pre>
6
2012-12-26T15:11:20Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
26,354,620
<p>I was asking myself the same question few times. And even though the guys here tried hard to explain it, IMHO the best answer (and simplest) answer I have found is the <a href="https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod" rel="nofollow">description</a> of the Class method in the Python Documentation.</p> <p>There is also reference to the Static method. And in case someone already know instance methods (which I assume), this answer might be the final piece to put it all together...</p> <p>Further and deeper elaboration on this topic can be found also in the documentation: <a href="https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">The standard type hierarchy</a> (scroll down to <em>Instance methods</em> section)</p>
0
2014-10-14T07:07:55Z
[ "python", "class-method" ]
What are Class methods in Python for?
38,238
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
194
2008-09-01T18:16:41Z
39,381,275
<p>A class defines a set of instances, of course. And the methods of a class work on the individual instances. The class methods (and variables) a place to hang other information that is related to the set of instances over all.</p> <p>For example if your class defines a the set of students you might want class variables or methods which define things like the set of grade the students can be members of.</p> <p>You can also use class methods to define tools for working on the entire set. For example Student.all_of_em() might return all the known students. Obviously if your set of instances have more structure than just a set you can provide class methods to know about that structure. Students.all_of_em(grade='juniors')</p> <p>Techniques like this tend to lead to storing members of the set of instances into data structures that are rooted in class variables. You need to take care to avoid frustrating the garbage collection then.</p>
0
2016-09-08T01:29:19Z
[ "python", "class-method" ]
Retrieving an Oracle timestamp using Python's Win32 ODBC module
38,435
<p>Given an Oracle table created using the following:</p> <pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); </code></pre> <p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow">Win32 extensions</a> (from the win32all package), I tried the following:</p> <pre><code>import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() </code></pre> <p>When I run this, I get the following:</p> <pre><code>Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH </code></pre> <p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
2
2008-09-01T21:06:07Z
38,442
<p>My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a string:</p> <pre><code>cursor.execute("SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log") </code></pre> <p>This works, but isn't portable. I'd like to use the same Python script against a SQL Server database, so an Oracle-specific solution (such as TO_CHAR) won't work.</p>
1
2008-09-01T21:14:43Z
[ "python", "oracle", "ora-00932" ]
Retrieving an Oracle timestamp using Python's Win32 ODBC module
38,435
<p>Given an Oracle table created using the following:</p> <pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); </code></pre> <p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow">Win32 extensions</a> (from the win32all package), I tried the following:</p> <pre><code>import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() </code></pre> <p>When I run this, I get the following:</p> <pre><code>Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH </code></pre> <p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
2
2008-09-01T21:06:07Z
38,718
<p>I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the <code>TIMESTAMP WITH (LOCAL) TIME ZONE</code> data types, only the <code>TIMESTAMP</code> data type. As you have discovered, one workaround is in fact to use the <code>TO_CHAR</code> method.</p> <p>In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight <code>TIMESTAMP</code> column. If you don't have control over the table, another solution may be to create a view that converts from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code> via a string - sorry, I don't know if there is a way to convert directly from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code>.</p>
2
2008-09-02T02:33:57Z
[ "python", "oracle", "ora-00932" ]
What's the best way to return multiple values from a function in Python?
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
49
2008-09-01T22:01:02Z
38,513
<p>Returning a tuple is the usual way to do this in Python.</p>
7
2008-09-01T22:03:17Z
[ "python", "variables", "return" ]
What's the best way to return multiple values from a function in Python?
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
49
2008-09-01T22:01:02Z
38,514
<p>Return a tuple.</p> <pre><code>def f(x): # do stuff return (True, modified_string) success, modified_string = f(something) </code></pre>
14
2008-09-01T22:03:41Z
[ "python", "variables", "return" ]
What's the best way to return multiple values from a function in Python?
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
49
2008-09-01T22:01:02Z
38,516
<pre><code>def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking </code></pre>
105
2008-09-01T22:04:02Z
[ "python", "variables", "return" ]
What's the best way to return multiple values from a function in Python?
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
49
2008-09-01T22:01:02Z
38,524
<p>Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.</p> <p>But more directly to the point, if you throw an exception, you're forcing them to deal with the problem. If you try to return a value that indicates failure, it's very well possible somebody could not check the value and end up with some potentially hard to debug errors.</p>
27
2008-09-01T22:09:00Z
[ "python", "variables", "return" ]
What's the best way to return multiple values from a function in Python?
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
49
2008-09-01T22:01:02Z
38,760
<p>Throwing an exception for failure is one good way to proceed, and if you're returning a lot of different values, you can return a tuple. For the specific case you're citing, I often take an intermediate approach: return the modified string on success, and return None on failure. I'm enough of an unreconstructed C programmer to want to return a NULL pointer to char on failure.</p> <p>If I were writing a routine to be used as part of a larger library and consumed by other developers, I'd throw an exception on failure. When I'm eating my own dogfood, I'll probably return different types and test on return.</p>
3
2008-09-02T03:15:49Z
[ "python", "variables", "return" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
38,916
<p>The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.</p> <p>That said, here's what you have to do if you're determined to make this work:</p> <ol> <li><p>Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):</p> <pre><code>from django import forms from my_app.models import Product from django.contrib.admin import widgets class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() </code></pre></li> <li><p>Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).</p></li> <li><p>In the head of your template, include {{ form.media }} to output the links to the Javascript files.</p></li> <li><p>And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:</p> <pre><code>&lt;script type="text/javascript" src="/my_admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/admin/js/core.js"&gt;&lt;/script&gt; </code></pre> <p>You may also wish to use the following admin CSS (thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583">Alex</a> for mentioning this):</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/&gt; </code></pre></li> </ol> <p>This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.</p> <p>This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230">Jeremy</a> for pointing this out). Sample code for your URLconf:</p> <pre><code>(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), </code></pre> <p>Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:</p> <pre><code>{% load adminmedia %} /* At the top of the template. */ /* In the head section of the template. */ &lt;script type="text/javascript"&gt; window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; &lt;/script&gt; </code></pre> <p>Thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128">lupefiasco</a> for this addition.</p>
141
2008-09-02T06:10:58Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
72,284
<p>As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible.</p>
57
2008-09-16T13:39:39Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
408,230
<p>Yep, I ended up overriding the /admin/jsi18n/ url.</p> <p>Here's what I added in my urls.py. Make sure it's above the /admin/ url</p> <pre><code> (r'^admin/jsi18n', i18n_javascript), </code></pre> <p>And here is the i18n_javascript function I created.</p> <pre><code>from django.contrib import admin def i18n_javascript(request): return admin.site.i18n_javascript(request) </code></pre>
10
2009-01-02T22:53:21Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
719,583
<p>Complementing the answer by Carl Meyer, I would like to comment that you need to put that header in some valid block (inside the header) within your template.</p> <pre><code>{% block extra_head %} &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/&gt; &lt;script type="text/javascript" src="/admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/admin/js/core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/admin/js/admin/RelatedObjectLookups.js"&gt;&lt;/script&gt; {{ form.media }} {% endblock %} </code></pre>
6
2009-04-05T20:02:00Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
1,392,329
<p>I find myself referencing this post a lot, and found that the <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types" rel="nofollow">documentation</a> defines a <em>slightly</em> less hacky way to override default widgets. </p> <p>(<em>No need to override the ModelForm's __init__ method</em>)</p> <p>However, you still need to wire your JS and CSS appropriately as Carl mentions.</p> <p><strong>forms.py</strong></p> <pre><code>from django import forms from my_app.models import Product from django.contrib.admin import widgets class ProductForm(forms.ModelForm): mydate = forms.DateField(widget=widgets.AdminDateWidget) mytime = forms.TimeField(widget=widgets.AdminTimeWidget) mydatetime = forms.DateTimeField(widget=widgets.AdminSplitDateTime) class Meta: model = Product </code></pre> <p>Reference <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types" rel="nofollow">Field Types</a> to find the default form fields.</p>
8
2009-09-08T06:42:05Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
1,833,247
<p>Updated solution and workaround for <strong>SplitDateTime</strong> with <strong>required=False</strong>:</p> <p><em>forms.py</em></p> <pre><code>from django import forms class SplitDateTimeJSField(forms.SplitDateTimeField): def __init__(self, *args, **kwargs): super(SplitDateTimeJSField, self).__init__(*args, **kwargs) self.widget.widgets[0].attrs = {'class': 'vDateField'} self.widget.widgets[1].attrs = {'class': 'vTimeField'} class AnyFormOrModelForm(forms.Form): date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'})) time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'})) timestamp = SplitDateTimeJSField(required=False,) </code></pre> <p><em>form.html</em></p> <pre><code>&lt;script type="text/javascript" src="/admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin_media/js/core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin_media/js/calendar.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin_media/js/admin/DateTimeShortcuts.js"&gt;&lt;/script&gt; </code></pre> <p><em>urls.py</em></p> <pre><code>(r'^admin/jsi18n/', 'django.views.i18n.javascript_catalog'), </code></pre>
1
2009-12-02T14:29:53Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
2,396,907
<p>The below will also work as a last resort if the above failed</p> <pre><code>class PaymentsForm(forms.ModelForm): class Meta: model = Payments def __init__(self, *args, **kwargs): super(PaymentsForm, self).__init__(*args, **kwargs) self.fields['date'].widget = SelectDateWidget() </code></pre> <p>Same as </p> <pre><code> class PaymentsForm(forms.ModelForm): date = forms.DateField(widget=SelectDateWidget()) class Meta: model = Payments </code></pre> <p>put this in your forms.py <code>from django.forms.extras.widgets import SelectDateWidget</code></p>
3
2010-03-07T16:09:57Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
2,716,963
<p>I finally managed to get this widget working on the dev server, only to have it break on deployment. I finally decided it wasn't worth shoehorning into my site, and wrote my own widget. It's not as flexible, but it will probably work well for many: <a href="http://www.copiesofcopies.org/webl/?p=81" rel="nofollow">http://www.copiesofcopies.org/webl/?p=81</a></p>
4
2010-04-26T21:17:37Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
2,818,128
<p>Starting in Django 1.2 RC1, if you're using the Django admin date picker widge trick, the following has to be added to your template, or you'll see the calendar icon url being referenced through "/missing-admin-media-prefix/".</p> <pre><code>{% load adminmedia %} /* At the top of the template. */ /* In the head section of the template. */ &lt;script type="text/javascript"&gt; window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; &lt;/script&gt; </code></pre>
9
2010-05-12T11:03:15Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
3,284,874
<p>(I'm trying to comment on people suggesting to roll their own Calendar widget, but either I don't see the comment button, or I don't have enough rep.)</p> <p>What happened to <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>? I think it would be best to re-use the admin widget, but perhaps it should be separated from admin, and easier to use. Thanks for this information anyways.</p>
5
2010-07-19T20:38:24Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
9,139,017
<p>What about just assigning a class to your widget and then binding that class to the JQuery datepicker?</p> <p>Django forms.py:</p> <pre><code>class MyForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['my_date_field'].widget.attrs['class'] = 'datepicker' </code></pre> <p>And some JavaScript for the template:</p> <pre><code> $(".datepicker").datepicker(); </code></pre>
2
2012-02-04T06:50:50Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
11,446,609
<p>My head code for 1.4 version(some new and some removed)</p> <pre><code>{% block extrahead %} &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/global.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/&gt; &lt;script type="text/javascript" src="/admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/actions.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/calendar.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js"&gt;&lt;/script&gt; {% endblock %} </code></pre>
8
2012-07-12T07:06:08Z
[ "python", "django" ]
Using Django time/date widgets in custom form
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
147
2008-09-01T23:22:55Z
39,946,546
<p>In Django 10. myproject/urls.py: at the beginning of urlpatterns</p> <pre><code> from django.views.i18n import JavaScriptCatalog urlpatterns = [ url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), . . .] </code></pre> <p>In my template.html:</p> <pre><code>{% load staticfiles %} &lt;script src="{% static "js/jquery-2.2.3.min.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "js/bootstrap.min.js" %}"&gt;&lt;/script&gt; {# Loading internazionalization for js #} {% load i18n admin_modify %} &lt;script type="text/javascript" src="{% url 'javascript-catalog' %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/jquery.init.js" %}"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "/admin/css/base.css" %}"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "/admin/css/forms.css" %}"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "/admin/css/login.css" %}"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "/admin/css/widgets.css" %}"&gt; &lt;script type="text/javascript" src="{% static "/admin/js/core.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/SelectFilter2.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/admin/RelatedObjectLookups.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/actions.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/calendar.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static "/admin/js/admin/DateTimeShortcuts.js" %}"&gt;&lt;/script&gt; </code></pre>
0
2016-10-09T17:39:01Z
[ "python", "django" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
38,989
<pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} z = dict(x.items() + y.items()) print z </code></pre> <p>For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last.</p>
25
2008-09-02T07:49:27Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
38,990
<p>In your case, what you can do is:</p> <pre><code>z = dict(x.items() + y.items()) </code></pre> <p>This will, as you want it, put the final dict in <code>z</code>, and make the value for key <code>b</code> be properly overridden by the second (<code>y</code>) dict's value:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = dict(x.items() + y.items()) &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre> <p>If you use Python 3, it is only a little more complicated. To create <code>z</code>:</p> <pre><code>&gt;&gt;&gt; z = dict(list(x.items()) + list(y.items())) &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre>
1,292
2008-09-02T07:50:12Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
39,437
<p>An alternative:</p> <pre><code>z = x.copy() z.update(y) </code></pre>
472
2008-09-02T13:00:46Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
39,858
<p>Another, more concise, option:</p> <pre><code>z = dict(x, **y) </code></pre> <p><strong>Note</strong>: this has become a popular answer, but it is important to point out that if <code>y</code> has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, <a href="http://mail.python.org/pipermail/python-dev/2010-April/099459.html">Guido is not a fan</a>. So I can't recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely.</p>
209
2008-09-02T15:52:07Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
44,512
<p>I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it). Obviously this is not a single expression, but it is a single function call.</p> <pre><code>def merge(d1, d2, merge_fn=lambda x,y:y): """ Merges two dictionaries, non-destructively, combining values on duplicate keys as defined by the optional merge function. The default behavior replaces the values in d1 with corresponding values in d2. (There is no other generally applicable merge strategy, but often you'll have homogeneous types in your dicts, so specifying a merge technique can be valuable.) Examples: &gt;&gt;&gt; d1 {'a': 1, 'c': 3, 'b': 2} &gt;&gt;&gt; merge(d1, d1) {'a': 1, 'c': 3, 'b': 2} &gt;&gt;&gt; merge(d1, d1, lambda x,y: x+y) {'a': 2, 'c': 6, 'b': 4} """ result = dict(d1) for k,v in d2.iteritems(): if k in result: result[k] = merge_fn(result[k], v) else: result[k] = v return result </code></pre>
63
2008-09-04T19:08:25Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
49,492
<p>This probably won't be a popular answer, but you almost certainly do not want to do this. If you want a copy that's a merge, then use copy (or <a href="https://docs.python.org/2/library/copy.html">deepcopy</a>, depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit.</p> <p>In addition, when you use .items() (pre Python 3.0), you're creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item.</p> <p>In terms of <a href="https://docs.python.org/2/library/timeit.html">time</a>:</p> <pre><code>&gt;&gt;&gt; timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 15.52571702003479 &gt;&gt;&gt; timeit.Timer("temp = x.copy()\ntemp.update(y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 15.694622993469238 &gt;&gt;&gt; timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 41.484580039978027 </code></pre> <p>IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions.</p>
136
2008-09-08T11:16:54Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
228,366
<p>In a follow-up answer, you asked about the relative performance of these two alternatives:</p> <pre><code>z1 = dict(x.items() + y.items()) z2 = dict(x, **y) </code></pre> <p>On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative <code>z2</code> is not only shorter and simpler but also significantly faster. You can verify this for yourself using the <code>timeit</code> module that comes with Python.</p> <p>Example 1: identical dictionaries mapping 20 consecutive integers to themselves:</p> <pre><code>% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())' 100000 loops, best of 3: 5.67 usec per loop % python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)' 100000 loops, best of 3: 1.53 usec per loop </code></pre> <p><code>z2</code> wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but <code>z2</code> always seems to come out ahead. (If you get inconsistent results for the <em>same</em> test, try passing in <code>-r</code> with a number larger than the default 3.)</p> <p>Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:</p> <pre><code>% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())' 1000 loops, best of 3: 260 usec per loop % python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)' 10000 loops, best of 3: 26.9 usec per loop </code></pre> <p><code>z2</code> wins by about a factor of 10. That's a pretty big win in my book!</p> <p>After comparing those two, I wondered if <code>z1</code>'s poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:</p> <pre><code>from itertools import chain z3 = dict(chain(x.iteritems(), y.iteritems())) </code></pre> <p>A few quick tests, e.g.</p> <pre><code>% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))' 10000 loops, best of 3: 66 usec per loop </code></pre> <p>lead me to conclude that <code>z3</code> is somewhat faster than <code>z1</code>, but not nearly as fast as <code>z2</code>. Definitely not worth all the extra typing.</p> <p>This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the <code>update</code> method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:</p> <pre><code>z0 = dict(x) z0.update(y) </code></pre> <p>A typical result:</p> <pre><code>% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)' 10000 loops, best of 3: 26.9 usec per loop </code></pre> <p>In other words, <code>z0</code> and <code>z2</code> seem to have essentially identical performance. Do you think this might be a coincidence? I don't....</p> <p>In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses <code>dict</code> in lots of places; optimizing its operations is a big deal.</p> <p>You could also write this as</p> <pre><code>z0 = x.copy() z0.update(y) </code></pre> <p>as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand.</p>
86
2008-10-23T02:38:56Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
3,936,548
<p>The best version I could think while not using copy would be:</p> <pre><code>from itertools import chain x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} dict(chain(x.iteritems(), y.iteritems())) </code></pre> <p>It's faster than <code>dict(x.items() + y.items())</code> but not as fast as <code>n = copy(a); n.update(b)</code>, at least on CPython. This version also works in Python 3 if you change <code>iteritems()</code> to <code>items()</code>, which is automatically done by the 2to3 tool.</p> <p>Personally I like this version best because it describes fairly good what I want in a single functional syntax. The only minor problem is that it doesn't make completely obvious that values from y takes precedence over values from x, but I don't believe it's difficult to figure that out.</p>
39
2010-10-14T18:55:15Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
7,770,473
<p>While the question has already been answered several times, this simple solution to the problem has not been listed yet.</p> <pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} z4 = {} z4.update(x) z4.update(y) </code></pre> <p>It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change.</p>
22
2011-10-14T16:12:33Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
8,247,023
<p>If you think lambdas are evil then read no further. As requested, you can write the fast and memory-efficient solution with one expression:</p> <pre><code>x = {'a':1, 'b':2} y = {'b':10, 'c':11} z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y) print z {'a': 1, 'c': 11, 'b': 10} print x {'a': 1, 'b': 2} </code></pre> <p>As suggested above, using two lines or writing a function is probably a better way to go.</p>
15
2011-11-23T18:08:23Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
8,310,229
<h1>Recursively/deep update a dict</h1> <pre><code>def deepupdate(original, update): """ Recursively update a dict. Subdict's won't be overwritten but also updated. """ for key, value in original.iteritems(): if key not in update: update[key] = value elif isinstance(value, dict): deepupdate(value, update[key]) return update</code></pre> <p>Demonstration:</p> <pre><code>pluto_original = { 'name': 'Pluto', 'details': { 'tail': True, 'color': 'orange' } } pluto_update = { 'name': 'Pluutoo', 'details': { 'color': 'blue' } } print deepupdate(pluto_original, pluto_update)</code></pre> <p>Outputs:</p> <pre><code>{ 'name': 'Pluutoo', 'details': { 'color': 'blue', 'tail': True } }</code></pre> <p>Thanks rednaw for edits.</p>
32
2011-11-29T11:52:15Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
11,804,613
<p>Even though the answers were good for this <em>shallow</em> dictionary, none of the methods defined here actually do a deep dictionary merge.</p> <p>Examples follow:</p> <pre><code>a = { 'one': { 'depth_2': True }, 'two': True } b = { 'one': { 'extra': False } } print dict(a.items() + b.items()) </code></pre> <p>One would expect a result of something like this:</p> <pre><code>{ 'one': { 'extra': False', 'depth_2': True }, 'two': True } </code></pre> <p>Instead, we get this:</p> <pre><code>{'two': True, 'one': {'extra': False}} </code></pre> <p>The 'one' entry should have had 'depth_2' and 'extra' as items inside its dictionary if it truly was a merge.</p> <p>Using chain also, does not work:</p> <pre><code>from itertools import chain print dict(chain(a.iteritems(), b.iteritems())) </code></pre> <p>Results in:</p> <pre><code>{'two': True, 'one': {'extra': False}} </code></pre> <p>The deep merge that rcwesick gave also creates the same result.</p> <p>Yes, it will work to merge the sample dictionaries, but none of them are a generic mechanism to merge. I'll update this later once I write a method that does a true merge.</p>
5
2012-08-03T23:36:50Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
11,825,563
<pre><code>def dict_merge(a, b): c = a.copy() c.update(b) return c new = dict_merge(old, extras) </code></pre> <p>Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life <em>Guido van Rossum</em> himself! Someone else suggested half of this, but did not put it in a function.</p> <pre><code>print dict_merge( {'color':'red', 'model':'Mini'}, {'model':'Ferrari', 'owner':'Carl'}) </code></pre> <p>gives:</p> <pre><code>{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'} </code></pre>
19
2012-08-06T09:24:44Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
12,926,103
<p><strong>Two dictionaries</strong></p> <pre><code>def union2(dict1, dict2): return dict(list(dict1.items()) + list(dict2.items())) </code></pre> <p><strong><em>n</em> dictionaries</strong></p> <pre><code>def union(*dicts): return dict(itertools.chain.from_iterable(dct.items() for dct in dicts)) </code></pre> <p><code>sum</code> has bad performance. See <a href="https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/" rel="nofollow">https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/</a></p>
4
2012-10-17T02:09:45Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
16,259,217
<p>In Python 3, you can use <a href="http://docs.python.org/3/library/collections.html#collections.ChainMap"><em>collections.ChainMap</em></a> which groups multiple dicts or other mappings together to create a single, updateable view:</p> <pre><code>&gt;&gt;&gt; from collections import ChainMap &gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = ChainMap({}, y, x) &gt;&gt;&gt; for k, v in z.items(): print(k, '--&gt;', v) a --&gt; 1 b --&gt; 10 c --&gt; 11 </code></pre>
44
2013-04-28T03:15:38Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
16,769,722
<p>Using a dict comprehension, you may</p> <pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} dc = {xi:(x[xi] if xi not in list(y.keys()) else y[xi]) for xi in list(x.keys())+(list(y.keys()))} </code></pre> <p>gives</p> <pre><code>&gt;&gt;&gt; dc {'a': 1, 'c': 11, 'b': 10} </code></pre> <p>Note the syntax for <code>if else</code> in comprehension </p> <pre><code>{ (some_key if condition else default_key):(something_if_true if condition else something_if_false) for key, value in dict_.items() } </code></pre>
1
2013-05-27T09:04:20Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
17,587,183
<p>Here is some code, it seems to work ok:</p> <pre><code>def merge(d1, d2, mode=0): if not type(d2) is dict: raise Exception("d2 is not a dict") if not type(d1) is dict: if mode == 0: raise Exception("d1 is not a dict") return d2 result = dict(d1) for k, v in d2.iteritems(): if k in result and type(v) is dict: result[k] = merge(result[k], v, 1) else: if mode == 1: result.update(d2) else: result[k] = v return result </code></pre>
-2
2013-07-11T07:13:12Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
17,738,920
<p>Drawing on ideas here and elsewhere I've comprehended a function:</p> <pre><code>def merge(*dicts, **kv): return { k:v for d in list(dicts) + [kv] for k,v in d.items() } </code></pre> <p>Usage (tested in python 3):</p> <pre><code>assert (merge({1:11,'a':'aaa'},{1:99, 'b':'bbb'},foo='bar')==\ {1: 99, 'foo': 'bar', 'b': 'bbb', 'a': 'aaa'}) assert (merge(foo='bar')=={'foo': 'bar'}) assert (merge({1:11},{1:99},foo='bar',baz='quux')==\ {1: 99, 'foo': 'bar', 'baz':'quux'}) assert (merge({1:11},{1:99})=={1: 99}) </code></pre> <p>You could use a lambda instead.</p>
5
2013-07-19T05:49:19Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
18,114,065
<p>Abuse leading to a one-expression solution for <a href="http://stackoverflow.com/a/39437/15055">Matthew's answer</a>:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = (lambda f=x.copy(): (f.update(y), f)[1])() &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre> <p>You said you wanted one expression, so I abused <code>lambda</code> to bind a name, and tuples to override lambda's one-expression limit. Feel free to cringe.</p> <p>You could also do this of course if you don't care about copying it:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = (x.update(y), x)[1] &gt;&gt;&gt; z {'a': 1, 'b': 10, 'c': 11} </code></pre>
7
2013-08-07T21:23:08Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
18,665,968
<p><code>**</code> creates an intermediary dict, which means that the total number of copies is actually higher doing the <code>dict(one, **two)</code> form, but all that happens in C so it's still generally faster than going to itertools, unless there are a huge number of copies (or, probably, if the copies are very expensive). As always if you actually care about speed you should time your use case.</p> <p>Timing on Python 2.7.3 with an empty dict:</p> <pre><code>$ python -m timeit "dict({}, **{})" 1000000 loops, best of 3: 0.405 usec per loop $ python -m timeit -s "from itertools import chain" \ "dict(chain({}.iteritems(), {}.iteritems()))" 1000000 loops, best of 3: 1.18 usec per loop </code></pre> <p>With 10,000 (tiny) items:</p> <pre><code>$ python -m timeit -s 'd = {i: str(i) for i in xrange(10000)}' \ "dict(d, **d)" 1000 loops, best of 3: 550 usec per loop $ python -m timeit -s "from itertools import chain" -s 'd = {i: str(i) for i in xrange(10000)}' \ "dict(chain(d.iteritems(), d.iteritems()))" 1000 loops, best of 3: 1.11 msec per loop </code></pre> <p>With 100,000 items:</p> <pre><code>$ python -m timeit -s 'd = {i: str(i) for i in xrange(100000)}' \ "dict(d, **d)" 10 loops, best of 3: 19.6 msec per loop $ python -m timeit -s "from itertools import chain" -s 'd = {i: str(i) for i in xrange(100000)}' \ "dict(chain(d.iteritems(), d.iteritems()))" 10 loops, best of 3: 20.1 msec per loop </code></pre> <p>With 1,000,000 items:</p> <pre><code>$ python -m timeit -s 'd = {i: str(i) for i in xrange(1000000)}' \ "dict(d, **d)" 10 loops, best of 3: 273 msec per loop $ python -m timeit -s "from itertools import chain" -s 'd = {i: str(i) for i in xrange(1000000)}' \ "dict(chain(d.iteritems(), d.iteritems()))" 10 loops, best of 3: 233 msec per loop </code></pre>
1
2013-09-06T20:18:58Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
19,279,501
<p>In python3, the <code>items</code> method <a href="http://docs.python.org/dev/whatsnew/3.0.html#views-and-iterators-instead-of-lists">no longer returns a list</a>, but rather a <em>view</em>, which acts like a set. In this case you'll need to take the set union since concatenating with <code>+</code> won't work:</p> <pre><code>dict(x.items() | y.items()) </code></pre> <p>For python3-like behavior in version 2.7, the <code>viewitems</code> method should work in place of <code>items</code>:</p> <pre><code>dict(x.viewitems() | y.viewitems()) </code></pre> <p>I prefer this notation anyways since it seems more natural to think of it as a set union operation rather than concatenation (as the title shows).</p> <p><strong>Edit:</strong></p> <p>A couple more points for python 3. First, note that the <code>dict(x, **y)</code> trick won't work in python 3 unless the keys in <code>y</code> are strings.</p> <p>Also, Raymond Hettinger's Chainmap <a href="http://stackoverflow.com/a/16259217/386279">answer</a> is pretty elegant, since it can take an arbitrary number of dicts as arguments, but <a href="http://docs.python.org/dev/library/collections">from the docs</a> it looks like it sequentially looks through a list of all the dicts for each lookup:</p> <blockquote> <p>Lookups search the underlying mappings successively until a key is found.</p> </blockquote> <p>This can slow you down if you have a lot of lookups in your application:</p> <pre><code>In [1]: from collections import ChainMap In [2]: from string import ascii_uppercase as up, ascii_lowercase as lo; x = dict(zip(lo, up)); y = dict(zip(up, lo)) In [3]: chainmap_dict = ChainMap(y, x) In [4]: union_dict = dict(x.items() | y.items()) In [5]: timeit for k in union_dict: union_dict[k] 100000 loops, best of 3: 2.15 µs per loop In [6]: timeit for k in chainmap_dict: chainmap_dict[k] 10000 loops, best of 3: 27.1 µs per loop </code></pre> <p>So about an order of magnitude slower for lookups. I'm a fan of Chainmap, but looks less practical where there may be many lookups.</p>
10
2013-10-09T18:09:08Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
19,950,727
<pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; x, z = dict(x), x.update(y) or x &gt;&gt;&gt; x {'a': 1, 'b': 2} &gt;&gt;&gt; y {'c': 11, 'b': 10} &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre>
6
2013-11-13T10:01:31Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
20,358,548
<p>The problem I have with solutions listed to date is that, in the merged dictionary, the value for key "b" is 10 but, to my way of thinking, it should be 12. In that light, I present the following:</p> <pre><code>import timeit n=100000 su = """ x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} """ def timeMerge(f,su,niter): print "{:4f} sec for: {:30s}".format(timeit.Timer(f,setup=su).timeit(n),f) timeMerge("dict(x, **y)",su,n) timeMerge("x.update(y)",su,n) timeMerge("dict(x.items() + y.items())",su,n) timeMerge("for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] ",su,n) #confirm for loop adds b entries together x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] print "confirm b elements are added:",x </code></pre> <h1>Results:</h1> <pre><code>0.049465 sec for: dict(x, **y) 0.033729 sec for: x.update(y) 0.150380 sec for: dict(x.items() + y.items()) 0.083120 sec for: for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] confirm b elements are added: {'a': 1, 'c': 11, 'b': 12} </code></pre>
5
2013-12-03T18:11:54Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
20,394,520
<p>I have a solution which is not specified here(Man I LOVE python) :-)</p> <pre><code>z = {} z.update(x) or z.update(y) </code></pre> <p>This will not update x as well as y. Performance? I don't think it will be terribly slow :-)</p> <p>NOTE: It is supposed to be 'or' operation and not 'and' operation. Edited to correct the code.</p>
1
2013-12-05T08:02:05Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
22,122,836
<p>It's so silly that <code>.update</code> returns nothing.<br> I just use a simple helper function to solve the problem:</p> <pre><code>def merge(dict1,*dicts): for dict2 in dicts: dict1.update(dict2) return dict1 </code></pre> <p>Examples:</p> <pre><code>merge(dict1,dict2) merge(dict1,dict2,dict3) merge(dict1,dict2,dict3,dict4) merge({},dict1,dict2) # this one returns a new copy </code></pre>
2
2014-03-02T01:44:39Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
26,111,877
<p>A union of the OP's two dictionaries would be something like:</p> <pre><code>{'a': 1, 'b': 2, 10, 'c': 11} </code></pre> <p>Specifically, the union of two entities(<code>x</code> and <code>y</code>) contains all the elements of <code>x</code> and/or <code>y</code>. Unfortunately, what the OP asks for is not a union, despite the title of the post.</p> <p>My code below is neither elegant nor a one-liner, but I believe it is consistent with the meaning of union.</p> <p>From the OP's example:</p> <pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} z = {} for k, v in x.items(): if not k in z: z[k] = [(v)] else: z[k].append((v)) for k, v in y.items(): if not k in z: z[k] = [(v)] else: z[k].append((v)) {'a': [1], 'b': [2, 10], 'c': [11]} </code></pre> <p>Whether one wants lists could be changed, but the above will work if a dictionary contains lists (and nested lists) as values in either dictionary.</p>
1
2014-09-30T02:36:19Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
26,853,961
<blockquote> <h1>How can I merge two Python dictionaries in a single expression?</h1> </blockquote> <p>Say you have two dicts and you want to merge them into a new dict without altering the original dicts:</p> <pre><code>x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} </code></pre> <p>The desired result is to get a new dictionary (<code>z</code>) with the values merged, and the second dict's values overwriting those from the first.</p> <pre><code>&gt;&gt;&gt; z {'a': 1, 'b': 3, 'c': 4} </code></pre> <p>A new syntax for this, proposed in <a href="https://www.python.org/dev/peps/pep-0448">PEP 448</a> and <a href="https://mail.python.org/pipermail/python-dev/2015-February/138564.html">available as of Python 3.5</a>, is </p> <pre><code>z = {**x, **y} </code></pre> <p>And it is indeed a single expression. It is now showing as implemented in the <a href="https://www.python.org/dev/peps/pep-0478/#features-for-3-5">release schedule for 3.5, PEP 478</a>, and it has now made its way into <a href="https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations">What's New in Python 3.5</a> document.</p> <p>However, since many organizations are still on Python 2, you may wish to do this in a backwards compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:</p> <pre><code>z = x.copy() z.update(y) # which returns None since it mutates z </code></pre> <p>In both approaches, <code>y</code> will come second and its values will replace <code>x</code>'s values, thus <code>'b'</code> will point to <code>3</code> in our final result.</p> <h1>Not yet on Python 3.5, but want a <em>single expression</em></h1> <p>If you are not yet on Python 3.5, or need to write backward-compatible code, and you want this in a <em>single expression</em>, the most performant while correct approach is to put it in a function:</p> <pre><code>def merge_two_dicts(x, y): '''Given two dicts, merge them into a new dict as a shallow copy.''' z = x.copy() z.update(y) return z </code></pre> <p>and then you have a single expression:</p> <pre><code>z = merge_two_dicts(x, y) </code></pre> <p>You can also make a function to merge an undefined number of dicts, from zero to a very large number:</p> <pre><code>def merge_dicts(*dict_args): ''' Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. ''' result = {} for dictionary in dict_args: result.update(dictionary) return result </code></pre> <p>This function will work in Python 2 and 3 for all dicts. e.g. given dicts <code>a</code> to <code>g</code>:</p> <pre><code>z = merge_dicts(a, b, c, d, e, f, g) </code></pre> <p>and key value pairs in <code>g</code> will take precedence over dicts <code>a</code> to <code>f</code>, and so on.</p> <h1>Critiques of Other Answers</h1> <p>Don't use what you see in the most upvoted answer:</p> <pre><code>z = dict(x.items() + y.items()) </code></pre> <p>In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. <strong>In Python 3, this will fail</strong> because you're adding two <code>dict_items</code> objects together, not two lists - </p> <pre><code>&gt;&gt;&gt; c = dict(a.items() + b.items()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' </code></pre> <p>and you would have to explicitly create them as lists, e.g. <code>z = dict(list(x.items()) + list(y.items()))</code>. This is a waste of resources and computation power. </p> <p>Similarly, taking the union of <code>items()</code> in Python 3 (<code>viewitems()</code> in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, <strong>since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:</strong></p> <pre><code>&gt;&gt;&gt; c = dict(a.items() | b.items()) </code></pre> <p>This example demonstrates what happens when values are unhashable:</p> <pre><code>&gt;&gt;&gt; x = {'a': []} &gt;&gt;&gt; y = {'b': []} &gt;&gt;&gt; dict(x.items() | y.items()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unhashable type: 'list' </code></pre> <p>Here's an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:</p> <pre><code>&gt;&gt;&gt; x = {'a': 2} &gt;&gt;&gt; y = {'a': 1} &gt;&gt;&gt; dict(x.items() | y.items()) {'a': 2} </code></pre> <p>Another hack you should not use:</p> <pre><code>z = dict(x, **y) </code></pre> <p>This uses the <code>dict</code> constructor, and is very fast and memory efficient (even slightly more-so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic. <strong>Also, this fails in Python 3 when keys are not strings.</strong></p> <pre><code>&gt;&gt;&gt; c = dict(a, **b) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: keyword arguments must be strings </code></pre> <p>From the <a href="https://mail.python.org/pipermail/python-dev/2010-April/099459.html">mailing list</a>, Guido van Rossum, the creator of the language, wrote:</p> <blockquote> <p>I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.</p> </blockquote> <p>and </p> <blockquote> <p>Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally I find it more despicable than cool.</p> </blockquote> <h1>Less Performant But Correct Ad-hocs</h1> <p>These approaches are less performant, but they will provide correct behavior. They will be <em>much less</em> performant than <code>copy</code> and <code>update</code> or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they <em>do</em> respect the order of precedence (latter dicts have precedence)</p> <p>You can also chain the dicts manually inside a dict comprehension:</p> <pre><code>{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7 </code></pre> <p>or in python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):</p> <pre><code>dict((k, v) for d in dicts for k, v in d.items()) </code></pre> <p><code>itertools.chain</code> will chain the iterators over the key-value pairs in the correct order:</p> <pre><code>import itertools z = dict(itertools.chain(x.iteritems(), y.iteritems())) </code></pre> <h1>Performance Analysis</h1> <p>I'm only going to do the performance analysis of the usages known to behave correctly. </p> <pre><code>import timeit </code></pre> <p>The following is done on Ubuntu 14.04</p> <p>In Python 2.7 (system Python):</p> <pre><code>&gt;&gt;&gt; min(timeit.repeat(lambda: merge_two_dicts(x, y))) 0.5726828575134277 &gt;&gt;&gt; min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 1.163769006729126 &gt;&gt;&gt; min(timeit.repeat(lambda: dict(itertools.chain(x.iteritems(), y.iteritems())))) 1.1614501476287842 &gt;&gt;&gt; min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 2.2345519065856934 </code></pre> <p>In Python 3.5 (deadsnakes PPA):</p> <pre><code>&gt;&gt;&gt; min(timeit.repeat(lambda: {**x, **y})) 0.4094954460160807 &gt;&gt;&gt; min(timeit.repeat(lambda: merge_two_dicts(x, y))) 0.7881555100320838 &gt;&gt;&gt; min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 1.4525277839857154 &gt;&gt;&gt; min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items())))) 2.3143140770262107 &gt;&gt;&gt; min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 3.2069112799945287 </code></pre>
1,255
2014-11-10T22:11:48Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
28,753,078
<p>Python 3.5 (PEP 448) allows a nicer syntax option:</p> <pre><code>x = {'a': 1, 'b': 1} y = {'a': 2, 'c': 2} final = {**x, **y} final # {'a': 2, 'b': 1, 'c': 2} </code></pre> <p>Or even </p> <pre><code>final = {'a': 1, 'b': 1, **x, **y} </code></pre>
22
2015-02-26T21:27:52Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
29,177,685
<pre><code>a = {1: 2, 3: 4, 5: 6} b = {7:8, 1:2} combined = dict(a.items() + b.items()) print combined </code></pre>
2
2015-03-21T00:06:12Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
31,478,567
<p>This can be done with a single dict comprehension:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; { key: y[key] if key in y else x[key] for key in set(x) + set(y) } </code></pre> <p>In my view the best answer for the 'single expression' part as no extra functions are needed, and it is short.</p>
2
2015-07-17T14:47:23Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
31,812,635
<p>Simple solution using itertools that preserves order (latter dicts have precedence)</p> <pre><code>import itertools as it merge = lambda *args: dict(it.chain.from_iterable(it.imap(dict.iteritems, args))) </code></pre> <p>And it's usage:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; merge(x, y) {'a': 1, 'b': 10, 'c': 11} &gt;&gt;&gt; z = {'c': 3, 'd': 4} &gt;&gt;&gt; merge(x, y, z) {'a': 1, 'b': 10, 'c': 3, 'd': 4} </code></pre>
7
2015-08-04T14:54:58Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
33,999,337
<pre><code>from collections import Counter dict1 = {'a':1, 'b': 2} dict2 = {'b':10, 'c': 11} result = dict(Counter(dict1) + Counter(dict2)) </code></pre> <p>This should solve your problem.</p>
1
2015-11-30T13:04:00Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
34,899,183
<p>Be pythonic. Use a <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">comprehension</a>:</p> <pre><code>z={i:d[i] for d in [x,y] for i in d} &gt;&gt;&gt; print z {'a': 1, 'c': 11, 'b': 10} </code></pre>
3
2016-01-20T11:46:22Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
36,263,150
<p>(For Python2.7* only; there are simpler solutions for Python3*.)</p> <p>If you're not averse to importing a standard library module, you can do</p> <pre><code>from functools import reduce def merge_dicts(*dicts): return reduce(lambda a, d: a.update(d) or a, dicts, {}) </code></pre> <p>(The <code>or a</code> bit in the <code>lambda</code> is necessary because <code>dict.update</code> always returns <code>None</code> on success.)</p>
1
2016-03-28T13:13:27Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
37,304,637
<p>I know this does not really fit the specifics of the questions ("one liner"), but since <em>none</em> of the answers above went into this direction while lots and lots of answers addressed the performance issue, I felt I should contribute my thoughts.</p> <p>Depending on the use case it might not be necessary to create a "real" merged dictionary of the given input dictionaries. A <em>view</em> which does this might be sufficient in many cases, i. e. an object which acts <em>like</em> the merged dictionary would without computing it completely. A lazy version of the merged dictionary, so to speak.</p> <p>In Python, this is rather simple and can be done with the code shown at the end of my post. This given, the answer to the original question would be:</p> <pre><code>z = MergeDict(x, y) </code></pre> <p>When using this new object, it will behave like a merged dictionary but it will have constant creation time and constant memory footprint while leaving the original dictionaries untouched. Creating it is way cheaper than in the other solutions proposed.</p> <p>Of course, if you use the result a lot, then you will at some point reach the limit where creating a real merged dictionary would have been the faster solution. As I said, it depends on your use case.</p> <p>If you ever felt you would prefer to have a real merged <code>dict</code>, then calling <code>dict(z)</code> would produce it (but way more costly than the other solutions of course, so this is just worth mentioning).</p> <p>You can also use this class to make a kind of copy-on-write dictionary:</p> <pre><code>a = { 'x': 3, 'y': 4 } b = MergeDict(a) # we merge just one dict b['x'] = 5 print b # will print {'x': 5, 'y': 4} print a # will print {'y': 4, 'x': 3} </code></pre> <p>Here's the straight-forward code of <code>MergeDict</code>:</p> <pre><code>class MergeDict(object): def __init__(self, *originals): self.originals = ({},) + originals[::-1] # reversed def __getitem__(self, key): for original in self.originals: try: return original[key] except KeyError: pass raise KeyError(key) def __setitem__(self, key, value): self.originals[0][key] = value def __iter__(self): return iter(self.keys()) def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, ', '.join(repr(original) for original in reversed(self.originals))) def __str__(self): return '{%s}' % ', '.join( '%r: %r' % i for i in self.iteritems()) def iteritems(self): found = set() for original in self.originals: for k, v in original.iteritems(): if k not in found: yield k, v found.add(k) def items(self): return list(self.iteritems()) def keys(self): return list(k for k, _ in self.iteritems()) def values(self): return list(v for _, v in self.iteritems()) </code></pre>
1
2016-05-18T15:57:32Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
39,251,599
<p>For Python 2 :</p> <pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} z = dict(x.items()+y.items()) print(z) </code></pre> <p>For Python 3:</p> <pre><code>x = {'a':1, 'b': 2} y = {'b':10, 'c': 11} z = dict(x.items()|y.items()) print(z) </code></pre> <p>It gives output:<code>{'a': 1, 'c': 11, 'b': 10}</code></p>
0
2016-08-31T13:53:20Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
How to merge two Python dictionaries in a single expression?
38,987
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
1,867
2008-09-02T07:44:30Z
39,736,284
<p>In Python 3.5 you can use unpack <code>**</code> in order to create new dictionary. This method has no been showed in past answers. Also, it's better to use <code>{}</code> instead of <code>dict()</code>. Because <code>{}</code> is a python literal and <code>dict()</code> involves a function call.</p> <pre><code>dict1 = {'a':1} dict2 = {'b':2} new_dict = {**dict1, **dict2} &gt;&gt;&gt;new_dict {'a':1, 'a':2} </code></pre>
0
2016-09-28T00:33:55Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
39,089
<p>Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.</p>
2
2008-09-02T09:24:20Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
39,110
<p>I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:</p> <pre><code>from tempfile import mkstemp from shutil import move from os import remove, close def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with open(abs_path,'w') as new_file: with open(file_path) as old_file: for line in old_file: new_file.write(line.replace(pattern, subst)) close(fh) #Remove original file remove(file_path) #Move new file move(abs_path, file_path) </code></pre>
111
2008-09-02T09:42:21Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
39,113
<p>As lassevk suggests, write out the new file as you go, here is some example code:</p> <pre><code>fin = open("a.txt") fout = open("b.txt", "wt") for line in fin: fout.write( line.replace('foo', 'bar') ) fin.close() fout.close() </code></pre>
8
2008-09-02T09:42:57Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
290,494
<p>The shortest way would probably be to use the <a href="http://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput">fileinput module</a>. For example, the following adds line numbers to a file, in-place:</p> <pre><code>import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput.filelineno(), line), </code></pre> <p>What happens here is:</p> <ol> <li>The original file is moved to a backup file</li> <li>The standard output is redirected to the original file within the loop</li> <li>Thus any <code>print</code> statements write back into the original file</li> </ol> <p><code>fileinput</code> has more bells and whistles. For example, it can be used to automatically operate on all files in <code>sys.args[1:]</code>, without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a <code>with</code> statement.</p> <hr> <p>While <code>fileinput</code> is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.</p> <p>There are two options:</p> <ol> <li>The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.</li> <li>The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.</li> </ol>
182
2008-11-14T15:47:40Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
315,088
<p>Here's another example that was tested, and will match search &amp; replace patterns:</p> <pre><code>import fileinput import sys def replaceAll(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=1): if searchExp in line: line = line.replace(searchExp,replaceExp) sys.stdout.write(line) </code></pre> <p>Example use:</p> <pre><code>replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.") </code></pre>
52
2008-11-24T19:02:28Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
1,388,570
<p>This should work: (inplace editing)</p> <pre><code>import fileinput # Does a list of files, and # redirects STDOUT to the file in question for line in fileinput.input(files, inplace = 1): print line.replace("foo", "bar"), </code></pre>
30
2009-09-07T10:07:25Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
11,784,227
<p>if you remove the indent at the like below, it will search and replace in multiple line. See below for example.</p> <pre><code>def replace(file, pattern, subst): #Create temp file fh, abs_path = mkstemp() print fh, abs_path new_file = open(abs_path,'w') old_file = open(file) for line in old_file: new_file.write(line.replace(pattern, subst)) #close temp file new_file.close() close(fh) old_file.close() #Remove original file remove(file) #Move new file move(abs_path, file) </code></pre>
0
2012-08-02T19:12:12Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
13,641,746
<p>Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis </p> <p>This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.</p> <p>Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.</p> <p>Reading the file as a single string instead of line by line allows for multiline match and replacement.</p> <pre><code>import re def replace(file, pattern, subst): # Read contents from file as a single string file_handle = open(file, 'r') file_string = file_handle.read() file_handle.close() # Use RE package to allow for replacement (also allowing for (multiline) REGEX) file_string = (re.sub(pattern, subst, file_string)) # Write contents to file. # Using mode 'w' truncates the file. file_handle = open(file, 'w') file_handle.write(file_string) file_handle.close() </code></pre>
13
2012-11-30T08:51:17Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
18,676,598
<p>A more pythonic way would be to use context managers like the code below:</p> <pre><code>from tempfile import mkstemp from shutil import move from os import remove def replace(source_file_path, pattern, substring): fh, target_file_path = mkstemp() with open(target_file_path, 'w') as target_file: with open(source_file_path, 'r') as source_file: for line in source_file: target_file.write(line.replace(pattern, substring)) remove(source_file_path) move(target_file_path, source_file_path) </code></pre> <p>You can find the full snippet <a href="https://gist.github.com/kirang89/6478017" rel="nofollow">here</a>.</p>
6
2013-09-07T18:39:01Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
21,857,132
<p>If you're wanting a generic function that replaces <em>any</em> text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:</p> <pre><code>import re def replace( filePath, text, subs, flags=0 ): with open( filePath, "r+" ) as file: fileContents = file.read() textPattern = re.compile( re.escape( text ), flags ) fileContents = textPattern.sub( subs, fileContents ) file.seek( 0 ) file.truncate() file.write( fileContents ) </code></pre>
7
2014-02-18T14:43:02Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
23,123,426
<p>Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.</p> <pre><code>import re fin = open("in.txt", 'r') # in file fout = open("out.txt", 'w') # out file for line in fin: p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern newline = p.sub('',line) # replace matching strings with empty string print newline fout.write(newline) fin.close() fout.close() </code></pre>
0
2014-04-17T02:13:32Z
[ "python", "file" ]
Search and replace a line in a file in Python
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
170
2008-09-02T09:19:04Z
23,426,834
<p>Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:</p> <pre><code>import codecs from tempfile import mkstemp from shutil import move from os import remove def replace(source_file_path, pattern, substring): fh, target_file_path = mkstemp() with codecs.open(target_file_path, 'w', 'utf-8') as target_file: with codecs.open(source_file_path, 'r', 'utf-8') as source_file: for line in source_file: target_file.write(line.replace(pattern, substring)) remove(source_file_path) move(target_file_path, source_file_path) </code></pre>
2
2014-05-02T11:15:57Z
[ "python", "file" ]
Finding a file in a Python module distribution
39,104
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p> <p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p> <pre> dbname = os.path.join(os.path.dirname(__file__), "database.dat") </pre> <p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
12
2008-09-02T09:40:26Z
39,295
<p>That's probably the way to do it, without resorting to something more advanced like using setuptools to install the files where they belong.</p> <p>Notice there's a problem with that approach, because on OSes with real a security framework (UNIXes, etc.) the user running your script might not have the rights to access the DB in the system directory where it gets installed.</p>
4
2008-09-02T11:43:45Z
[ "python", "distutils" ]
Finding a file in a Python module distribution
39,104
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p> <p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p> <pre> dbname = os.path.join(os.path.dirname(__file__), "database.dat") </pre> <p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
12
2008-09-02T09:40:26Z
39,659
<p>Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now):</p> <pre><code>&gt;&gt;&gt; import pkg_resources &gt;&gt;&gt; pkg_resources.resource_ filename(__name__, "foo.config") 'foo.config' &gt;&gt;&gt; pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' </code></pre> <p>There's more discussion about using pkg_resources to get resources on the <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources">eggs</a> page and the <a href="http://peak.telecommunity.com/DevCenter/PkgResources">pkg_resources</a> page.</p> <p>Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.</p>
14
2008-09-02T14:26:07Z
[ "python", "distutils" ]
Finding a file in a Python module distribution
39,104
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p> <p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p> <pre> dbname = os.path.join(os.path.dirname(__file__), "database.dat") </pre> <p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
12
2008-09-02T09:40:26Z
9,918,496
<p>Use <code>pkgutil.get_data</code>. It’s the cousin of <code>pkg_resources.resource_stream</code>, but in the standard library, and should work with flat filesystem installs as well as zipped packages and other importers.</p>
9
2012-03-29T02:52:42Z
[ "python", "distutils" ]
What is the best way to do Bit Field manipulation in Python?
39,663
<p>I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C).</p> <p>Suggestions?</p>
25
2008-09-02T14:28:40Z
39,760
<p>It's an often-asked question. There's an <a href="http://code.activestate.com/recipes/113799/">ASPN Cookbook</a> entry on it that has served me in the past.</p> <p>And there is an <a href="http://wiki.python.org/moin/BitManipulation">extensive page of requirements one person would like to see from a module doing this.</a></p>
7
2008-09-02T15:13:44Z
[ "python", "udp", "bits", "bit-fields" ]
What is the best way to do Bit Field manipulation in Python?
39,663
<p>I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C).</p> <p>Suggestions?</p>
25
2008-09-02T14:28:40Z
1,086,668
<p>The <a href="http://python-bitstring.googlecode.com">bitstring</a> module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well.</p> <p>A relevant example for you might be this, which strips out all the null packets from a transport stream (and quite possibly uses your 13 bit field?):</p> <pre><code>from bitstring import Bits, BitStream # Opening from a file means that it won't be all read into memory s = Bits(filename='test.ts') outfile = open('test_nonull.ts', 'wb') # Cut the stream into 188 byte packets for packet in s.cut(188*8): # Take a 13 bit slice and interpret as an unsigned integer PID = packet[11:24].uint # Write out the packet if the PID doesn't indicate a 'null' packet if PID != 8191: # The 'bytes' property converts back to a string. outfile.write(packet.bytes) </code></pre> <p>Here's another example including reading from bitstreams: </p> <pre><code># You can create from hex, binary, integers, strings, floats, files... # This has a hex code followed by two 12 bit integers s = BitStream('0x000001b3, uint:12=352, uint:12=288') # Append some other bits s += '0b11001, 0xff, int:5=-3' # read back as 32 bits of hex, then two 12 bit unsigned integers start_code, width, height = s.readlist('hex:32, 2*uint:12') # Skip some bits then peek at next bit value s.pos += 4 if s.peek(1): flags = s.read(9) </code></pre> <p>You can use standard slice notation to slice, delete, reverse, overwrite, etc. at the bit level, and there are bit level find, replace, split etc. functions. Different endiannesses are also supported.</p> <pre><code># Replace every '1' bit by 3 bits s.replace('0b1', '0b001') # Find all occurrences of a bit sequence bitposlist = list(s.findall('0b01000')) # Reverse bits in place s.reverse() </code></pre> <p>The full documentation is <a href="http://packages.python.org/bitstring/">here</a>.</p>
25
2009-07-06T12:20:13Z
[ "python", "udp", "bits", "bit-fields" ]
Using C in a shared multi-platform POSIX environment
39,847
<p>I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.</p> <p>One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.</p> <p>Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?</p> <p><em>Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.</em></p>
2
2008-09-02T15:46:39Z
39,865
<p>You know, you should look at static linking.</p> <p>These days, we all have HUGE hard drives, and a few extra megabytes (for carrying around libc and what not) is really not that big a deal anymore. </p> <p>You could also try running your applications in chroot() jails and distributing those.</p>
0
2008-09-02T15:58:10Z
[ "python", "c", "cross-platform", "posix", "scripting" ]
Using C in a shared multi-platform POSIX environment
39,847
<p>I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.</p> <p>One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.</p> <p>Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?</p> <p><em>Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.</em></p>
2
2008-09-02T15:46:39Z
39,871
<p>Depending on your mix os OSes, you might be better off creating packages for each class of system.</p> <p>Alternatively, if they all share the same ABI and hardware architecture, you could also compile static binaries.</p>
0
2008-09-02T15:59:52Z
[ "python", "c", "cross-platform", "posix", "scripting" ]
Using C in a shared multi-platform POSIX environment
39,847
<p>I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.</p> <p>One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.</p> <p>Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?</p> <p><em>Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.</em></p>
2
2008-09-02T15:46:39Z
39,878
<p>Also, you could use autoconf and distribute your application in source form only. :)</p>
1
2008-09-02T16:03:04Z
[ "python", "c", "cross-platform", "posix", "scripting" ]
Using C in a shared multi-platform POSIX environment
39,847
<p>I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.</p> <p>One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.</p> <p>Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?</p> <p><em>Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.</em></p>
2
2008-09-02T15:46:39Z
40,367
<p>Launching a Python interpreter instance just to select the right binary to run would be much heavier than you need. I'd distribute a shell .rc file which provides aliases.</p> <p>In /shared/bin, you put the various binaries: /shared/bin/toolname-mac, /shared/bin/toolname-debian-x86, /shared/bin/toolname-netbsd-dreamcast, etc. Then, in the common shared shell .rc file, you put the logic to set the aliases according to platform, so that on OSX, it gets alias toolname=/shared/bin/toolname-mac, and so forth.</p> <p>This won't work as well if you're adding new tools all the time, because the users will need to reload the aliases.</p> <p>I wouldn't recommend distributing tools this way, though. Testing and qualifying new builds of the tools should be taking up enough time and effort that the extra time required to distribute the tools to the users is trivial. You seem to be optimizing to reduce the distribution time. Replacing tools that quickly in a live environment is all too likely to result in lengthy and confusing downtime if anything goes wrong in writing and building the tools--especially when subtle cross-platform issues creep in.</p>
2
2008-09-02T19:29:07Z
[ "python", "c", "cross-platform", "posix", "scripting" ]
PGP signatures from Python?
39,929
<p>What is the easiest way to create and verify PGP/GPG signatures from within a Python application? </p> <p>I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).</p>
5
2008-09-02T16:19:11Z
40,069
<p>I think <a href="http://www.gnupg.org/related_software/gpgme/" rel="nofollow">GPGME</a> and the <a href="http://pyme.sourceforge.net/" rel="nofollow">PyMe Python wrapper</a> should do what you need.</p>
8
2008-09-02T17:15:23Z
[ "python", "security", "cross-platform", "gnupg" ]
PGP signatures from Python?
39,929
<p>What is the easiest way to create and verify PGP/GPG signatures from within a Python application? </p> <p>I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).</p>
5
2008-09-02T16:19:11Z
4,849,894
<p>In addition to PyMe, consider <a href="http://code.google.com/p/python-gnupg/" rel="nofollow">python-gnupg</a> and the <a href="http://py-gnupg.sourceforge.net/" rel="nofollow">gnupginterface</a>.</p>
2
2011-01-31T10:37:45Z
[ "python", "security", "cross-platform", "gnupg" ]
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
39,982
<p>Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this: </p> <pre><code>eval(s+"()"); </code></pre> <p>You just have to know that actually function <em>foo</em> exists.</p> <p><strong>Edit:</strong></p> <p>Don't use eval:) Use:</p> <pre><code>var functionName="myFunctionName"; window[functionName](); </code></pre>
4
2008-09-02T16:36:28Z
[ "javascript", "python" ]
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
39,992
<p>AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:</p> <pre><code>if (foo) foo(); </code></pre>
0
2008-09-02T16:41:56Z
[ "javascript", "python" ]
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
40,012
<p>I seem to remember Brendan Eich commented on this in a recent podcast; if i recall correctly, it's not being considered, as it adds unreasonable restrictions to optimization. He compared it to the <code>arguments</code> local in that, while useful for varargs, its very existence removes the ability to guess at what a function will touch just by looking at its definition. </p> <p>BTW: i believe JS <em>did</em> have support for accessing locals through the arguments local at one time - <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Functions/arguments" rel="nofollow">a quick search</a> shows this has been deprecated though.</p>
3
2008-09-02T16:50:34Z
[ "javascript", "python" ]