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
list
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
4,998,073
<p>I'm using <a href="https://bitbucket.org/izi/django-admin-tools/" rel="nofollow">django-admin-tools</a> for that.</p>
3
2011-02-14T22:33:21Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
5,819,110
<p>If you have more than one model in the app just create a model with the Meta information and create subclasses of that class for all your models.</p> <pre><code>class MyAppModel(models.Model): class Meta: app_label = 'My App Label' abstract = True class Category(MyAppModel): name = models.CharField(max_length=50) </code></pre>
30
2011-04-28T13:08:37Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
6,312,798
<p>For Django 1.4 (not yet released, but trunk is pretty stable), you can use the following method. It relies on the fact that AdminSite now returns a TemplateResponse, which you can alter before it is rendered.</p> <p>Here, we do a small bit of monkey patching to insert our behaviour, which can be avoided if you use a custom AdminSite subclass.</p> <pre><code>from functools import wraps def rename_app_list(func): m = {'Sites': 'Web sites', 'Your_app_label': 'Nicer app label', } @wraps(func) def _wrapper(*args, **kwargs): response = func(*args, **kwargs) app_list = response.context_data.get('app_list') if app_list is not None: for a in app_list: name = a['name'] a['name'] = m.get(name, name) title = response.context_data.get('title') if title is not None: app_label = title.split(' ')[0] if app_label in m: response.context_data['title'] = "%s administration" % m[app_label] return response return _wrapper admin.site.__class__.index = rename_app_list(admin.site.__class__.index) admin.site.__class__.app_index = rename_app_list(admin.site.__class__.app_index) </code></pre> <p>This fixes the index and the app_index views. It doesn't fix the bread crumbs in all other admin views.</p>
7
2011-06-10T22:47:20Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
22,150,764
<p>If you already have existing tables using the old app name, and you don't want to migrate them, then just set the app_label on a proxy of the original model.</p> <pre><code>class MyOldModel(models.Model): pass class MyNewModel(MyOldModel): class Meta: proxy = True app_label = 'New APP name' verbose_name = MyOldModel._meta.verbose_name </code></pre> <p>Then you just have to change this in your admin.py:</p> <pre><code>#admin.site.register(MyOldModel, MyOldModelAdmin) admin.site.register(MyNewModel, MyOldModelAdmin) </code></pre> <p><strong>Be aware that the url will be /admin/NewAPPname/mynewmodel/ so you might just want to make sure that the class name for the new model looks as close to the old model as possible.</strong></p>
2
2014-03-03T15:32:11Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
25,786,187
<p>There is a hack that can be done that does not require any migrations. Taken from Ionel's blog and credit goes to him: <a href="http://blog.ionelmc.ro/2011/06/24/custom-app-names-in-the-django-admin/" rel="nofollow">http://blog.ionelmc.ro/2011/06/24/custom-app-names-in-the-django-admin/</a></p> <p>There is also a ticket for this that should be fixed in Django 1.7 <a href="https://code.djangoproject.com/ticket/3591" rel="nofollow">https://code.djangoproject.com/ticket/3591</a></p> <p>"""</p> <p>Suppose you have a model like this:</p> <pre><code>class Stuff(models.Model): class Meta: verbose_name = u'The stuff' verbose_name_plural = u'The bunch of stuff' </code></pre> <p>You have verbose_name, however you want to customise app_label too for different display in admin. Unfortunatelly having some arbitrary string (with spaces) doesn't work and it's not for display anyway.</p> <p>Turns out that the admin uses app_label. title () for display so we can make a little hack: str subclass with overriden title method:</p> <pre><code>class string_with_title(str): def __new__(cls, value, title): instance = str.__new__(cls, value) instance._title = title return instance def title(self): return self._title __copy__ = lambda self: self __deepcopy__ = lambda self, memodict: self </code></pre> <p>Now we can have the model like this:</p> <pre><code>class Stuff(models.Model): class Meta: app_label = string_with_title("stuffapp", "The stuff box") # 'stuffapp' is the name of the django app verbose_name = 'The stuff' verbose_name_plural = 'The bunch of stuff' </code></pre> <p>and the admin will show "The stuff box" as the app name.</p> <p>"""</p>
3
2014-09-11T11:24:43Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
26,988,256
<p>first you need to create a apps.py file like this on your appfolder.</p> <pre><code># appName/apps.py # -*- coding: utf-8 -*- from django.apps import AppConfig class AppNameConfig(AppConfig): name = 'appName' verbose_name = "app Custom Name" </code></pre> <p>to load this AppConfig subclass by default:</p> <pre><code># appName/__init__.py default_app_config = 'appName.apps.AppNameConfig' </code></pre> <p>is the best way to do. tested on Django 1.7</p> <p><img src="http://i.stack.imgur.com/oDC6H.png" alt="My custom App Name"></p> <p><strong>For the person who had problems with the Spanish</strong></p> <p>This code enable the utf-8 compatibility on python scripts</p> <pre><code># -*- coding: utf-8 -*- </code></pre>
5
2014-11-18T06:48:03Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
27,254,978
<p>As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7</p> <p>Taken from the <a href="https://docs.djangoproject.com/en/1.7/ref/applications/#for-application-authors">docs</a>:</p> <pre class="lang-py prettyprint-override"><code># in yourapp/apps.py from django.apps import AppConfig class YourAppConfig(AppConfig): name = 'yourapp' verbose_name = 'Fancy Title' </code></pre> <p>then set the <code>default_app_config</code> variable to <code>YourAppConfig</code></p> <pre class="lang-py prettyprint-override"><code># in yourapp/__init__.py default_app_config = 'yourapp.apps.YourAppConfig' </code></pre>
19
2014-12-02T17:05:26Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
27,784,446
<p>The following plug-and-play piece of code works perfectly since <code>Django 1.7</code>. All you have to do is copy the below code in the <code>__init__.py</code> file of the specific app and change the <code>VERBOSE_APP_NAME</code> parameter.</p> <pre><code>from os import path from django.apps import AppConfig VERBOSE_APP_NAME = "YOUR VERBOSE APP NAME HERE" def get_current_app_name(file): return path.dirname(file).replace('\\', '/').split('/')[-1] class AppVerboseNameConfig(AppConfig): name = get_current_app_name(__file__) verbose_name = VERBOSE_APP_NAME default_app_config = get_current_app_name(__file__) + '.__init__.AppVerboseNameConfig' </code></pre> <p>If you use this for multiple apps, you should factor out the <code>get_current_app_name</code> function to a helper file.</p>
0
2015-01-05T17:09:34Z
[ "python", "django" ]
Problem using super(python 2.5.2)
612,468
<p>I'm writing a plugin system for my program and I can't get past one thing:</p> <pre><code>class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper import loadClasses classList=loadClasses('./plugins', IPlugin)#Gets a list of #plugin classes self.plugins={}#Dictionary that should be filled with #touples of objects and theirs states, activated, deactivated. classList[0](self)#Runs nicelly foo = classList[1] print foo#prints &lt;class 'TestPlugin.TestPlugin'&gt; foo(self)#Raise an exception </code></pre> <p>The test plugin looks like this:</p> <pre><code>import diones.thingpad.plugin.IPlugin as plugin class TestPlugin(plugin.IPlugin): ''' classdocs ''' def __init__(self, loader): self.name='Test Plugin' super(TestPlugin, self).__init__(loader) </code></pre> <p>Now the IPlugin looks like this:</p> <pre><code>class IPlugin(object): ''' classdocs ''' name='' def __init__(self, loader): self.loader=loader def activate(self): pass </code></pre> <p>All the IPlugin classes works flawlessy by them selves, but when called by ThingLoader the program gets an exception:</p> <pre><code>File "./plugins\TestPlugin.py", line 13, in __init__ super(TestPlugin, self).__init__(loader) NameError: global name 'super' is not defined </code></pre> <p>I looked all around and I simply don't know what is going on.</p>
1
2009-03-04T21:18:13Z
612,668
<p>‘super’ is a builtin. Unless you went out of your way to delete builtins, you shouldn't ever see “global name 'super' is not defined”.</p> <p>I'm looking at your <a href="http://logdiones.blogspot.com/">user web link</a> where there is a dump of IntrospectionHelper. It's very hard to read without the indentation, but it looks like you may be doing exactly that:</p> <pre><code>built_in_list = ['__builtins__', '__doc__', '__file__', '__name__'] for i in built_in_list: if i in module.__dict__: del module.__dict__[i] </code></pre> <p>That's the original module dict you're changing there, not an informational copy you are about to return! Delete these members from a live module and you can expect much more than ‘super’ to break.</p> <p>It's very hard to keep track of what that module is doing, but my reaction is there is far too much magic in it. The average Python program should never need to be messing around with the import system, sys.path, and monkey-patching __magic__ module members. A little bit of magic can be a neat trick, but this is extremely fragile. Just off the top of my head from browsing it, the code could be broken by things like:</p> <ul> <li>name clashes with top-level modules</li> <li>any use of new-style classes</li> <li>modules supplied only as compiled bytecode</li> <li>zipimporter</li> </ul> <p>From the incredibly round-about functions like getClassDefinitions, extractModuleNames and isFromBase, it looks to me like you still have quite a bit to learn about the basics of how Python works. (Clues: getattr, module.__name__ and issubclass, respectively.)</p> <p>In this case now is <em>not</em> the time to be diving into import magic! It's <em>hard</em>. Instead, do things The Normal Python Way. It may be a little more typing to say at the bottom of a package's mypackage/__init__.py:</p> <pre><code>from mypackage import fooplugin, barplugin, bazplugin plugins= [fooplugin.FooPlugin, barplugin.BarPlugin, bazplugin.BazPlugin] </code></pre> <p>but it'll work and be understood everywhere without relying on a nest of complex, fragile magic.</p> <p>Incidentally, unless you are planning on some in-depth multiple inheritance work (and again, now may not be the time for that), you probably don't even need to use super(). The usual “IPlugin.__init__(self, ...)” method of calling a known superclass is the straightforward thing to do; super() is not always “the newer, better way of doing things” and <a href="http://fuhm.net/super-harmful/">there are things you should understand about it</a> before you go charging into using it.</p>
20
2009-03-04T22:02:24Z
[ "python", "introspection", "python-datamodel" ]
Problem using super(python 2.5.2)
612,468
<p>I'm writing a plugin system for my program and I can't get past one thing:</p> <pre><code>class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper import loadClasses classList=loadClasses('./plugins', IPlugin)#Gets a list of #plugin classes self.plugins={}#Dictionary that should be filled with #touples of objects and theirs states, activated, deactivated. classList[0](self)#Runs nicelly foo = classList[1] print foo#prints &lt;class 'TestPlugin.TestPlugin'&gt; foo(self)#Raise an exception </code></pre> <p>The test plugin looks like this:</p> <pre><code>import diones.thingpad.plugin.IPlugin as plugin class TestPlugin(plugin.IPlugin): ''' classdocs ''' def __init__(self, loader): self.name='Test Plugin' super(TestPlugin, self).__init__(loader) </code></pre> <p>Now the IPlugin looks like this:</p> <pre><code>class IPlugin(object): ''' classdocs ''' name='' def __init__(self, loader): self.loader=loader def activate(self): pass </code></pre> <p>All the IPlugin classes works flawlessy by them selves, but when called by ThingLoader the program gets an exception:</p> <pre><code>File "./plugins\TestPlugin.py", line 13, in __init__ super(TestPlugin, self).__init__(loader) NameError: global name 'super' is not defined </code></pre> <p>I looked all around and I simply don't know what is going on.</p>
1
2009-03-04T21:18:13Z
612,676
<p>Unless you're running a version of Python earlier than 2.2 (pretty unlikely), <code>super()</code> is definitely a <a href="http://docs.python.org/library/functions.html" rel="nofollow">built-in function</a> (available in every scope, and without importing anything).</p> <p>May be worth checking your version of Python (just start up the interactive prompt by typing python at the command line).</p>
0
2009-03-04T22:05:07Z
[ "python", "introspection", "python-datamodel" ]
Code samples for Django + SWFUpload?
612,734
<p>Does anyone have any simple code samples for Django + <a href="http://swfupload.org/" rel="nofollow">SWFUpload</a>? I have it working perfectly in my PHP application but Django is giving me headaches.</p>
5
2009-03-04T22:21:07Z
612,898
<p>Unfortunately I can't give you any very detailed code samples, but I have quite a bit of experience with working with SWFUpload + Django (for a photo sharing site I work on). Anyway, here are a few pointers that will hopefully help you on your quest for DjSWF happiness :)</p> <ol> <li><p>You'll want to use the cookies plugin (if of course you are using some sort of session-based authentication [like <code>django.contrib.auth</code>, and care who uploaded what).</p> <p>The cookies plugin sends the data from cookies as POST, so you'll have to find some way of getting this back into <code>request.COOKIES</code> (<code>process_request</code> middleware that looks for a <code>settings.SESSION_COOKIE_NAME</code> in <code>request.POST</code> on specific URLs and dumps it into <code>request.COOKIES</code> works nicely for this :)</p></li> <li><p>Also, remember that you <em>must</em> return something in the response body for SWFUpload to recognize it as a successful upload attempt. I believe this has changed in the latest beta of SWFUpload, but anyway it's advisable just to stick something in there like 'ok'. For failures, make use of something like <code>HttpResponseBadRequest</code> or the like.</p></li> <li><p>Lastly, in case you're having trouble finding them, the uploaded file is in <code>request.FILES</code> :)</p></li> </ol> <p>If you have anything perplexing I haven't covered, feel free to post something more detailed and I'll be happy to help.</p>
17
2009-03-04T23:05:31Z
[ "python", "django", "swfupload" ]
Code samples for Django + SWFUpload?
612,734
<p>Does anyone have any simple code samples for Django + <a href="http://swfupload.org/" rel="nofollow">SWFUpload</a>? I have it working perfectly in my PHP application but Django is giving me headaches.</p>
5
2009-03-04T22:21:07Z
1,318,520
<p>Django version of the samples for SWFUpload:</p> <p><a href="http://github.com/naltimari/django-swfupload-samples/tree/master" rel="nofollow">http://github.com/naltimari/django-swfupload-samples/tree/master</a></p> <p>So long uploadify. Great idea but it is just buggy, especially on Windows.</p>
3
2009-08-23T13:06:52Z
[ "python", "django", "swfupload" ]
Code samples for Django + SWFUpload?
612,734
<p>Does anyone have any simple code samples for Django + <a href="http://swfupload.org/" rel="nofollow">SWFUpload</a>? I have it working perfectly in my PHP application but Django is giving me headaches.</p>
5
2009-03-04T22:21:07Z
24,508,069
<p>The following is my Django-specific implementation for fixing this issue (i.e. my uploads were failing in Firefox with a 302 Redirect).</p> <p>In my initial view that generates the page with the uploader on it, I looked at the cookies and found sessionid</p> <pre><code>ipdb&gt; self.request.COOKIES {'csrftoken': '43535f552b7c94563ada784f4d469acf', 'sessionid': 'rii380947wteuevuus0i5nbvpc6qq7i1'} </code></pre> <p>When I looked at what was being posted in the SWFUploadMiddleware (when using Firefox), I found that the sessionid was not being set.</p> <p>In my intial view that generates the page that contains the upload handler, I added the sessionid to the context.</p> <pre><code>context['sessionid'] = self.request.session.session_key </code></pre> <p>In my swfuploader settings, I added sessionid to the post-params option as follows:</p> <pre><code>post_params: {... "sessionid": "{{ sessionid }}" ...}, </code></pre> <p>Now, when I looked in the SWFUploadMiddleware, I could see the sessionid being posted, <strong>and my uploads started working if Firefox</strong>.</p> <pre><code>ipdb&gt; request.POST &lt;QueryDict: {... u'session_id': [u'rii380947wteuevuus0i5nbvpc6qq7i1'],...}&gt; </code></pre> <p>For completeness, my SWFUploadMiddleware looks like this...</p> <pre><code>from django.conf import settings from django.core.urlresolvers import reverse class SWFUploadMiddleware(object): def process_request(self, request): if (request.method == 'POST') and (request.path == reverse('upload_handler')) and request.POST.has_key(settings.SESSION_COOKIE_NAME): request.COOKIES[settings.SESSION_COOKIE_NAME] = request.POST[settings.SESSION_COOKIE_NAME] # http://stackoverflow.com/questions/6634666/403-forbidden-error-on-swfupload-and-django # Fix for problem uploading images (403 error) in Firefox 20 and others if request.POST.has_key('csrftoken'): request.COOKIES['csrftoken'] = request.POST['csrftoken'] </code></pre>
0
2014-07-01T10:32:48Z
[ "python", "django", "swfupload" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
613,012
<pre><code>python -c "import os; print os.listdir('.')" </code></pre> <p>If you want to apply some formatting like you have in your question,</p> <pre><code>python -c "import os; print '\n'.join(['&gt;&gt;%s' % x for x in os.listdir('.')])" </code></pre> <p>If you want to use a pipe, use <code>xargs</code>:</p> <pre><code>ls | xargs python -c "import sys; print '&gt;&gt;', sys.argv[1:]" </code></pre> <p>or backticks:</p> <pre><code>python -c "import sys; print '&gt;&gt;', sys.argv[1:]" `ls` </code></pre>
6
2009-03-04T23:47:33Z
[ "python", "cygwin", "cmd", "pipe" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
613,072
<p>You can read data piped <strong>into</strong> a Python script by reading sys.stdin. For example:</p> <pre><code>ls -al | python -c "import sys; print sys.stdin.readlines()" </code></pre> <p>It is not entirely clear what you want to do (maybe I am stupid). The confusion comes from your example which is piping data out of a python script.</p>
4
2009-03-05T00:06:43Z
[ "python", "cygwin", "cmd", "pipe" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
613,099
<p>If you want to print <em>all</em> files:</p> <pre><code>find . -type f </code></pre> <p>If you want to print only the current directory's files</p> <pre><code>find . -type f -maxdepth 1 </code></pre> <p>If you want to include the ">>" before each line</p> <pre><code>find . -type f -maxdepth 1 | xargs -L 1 echo "&gt;&gt;" </code></pre> <p>If you don't want the space between ">>" and $path from echo</p> <pre><code>find . -type f -maxdepth 1 | xargs -L 1 printf "&gt;&gt;%s\n" </code></pre> <p>This is all using cygwin, of course.</p>
4
2009-03-05T00:15:53Z
[ "python", "cygwin", "cmd", "pipe" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
613,134
<pre><code>ls | python -c "import sys; print sys.stdin.read()" </code></pre> <p>just read stdin as normal for pipes</p>
3
2009-03-05T00:29:16Z
[ "python", "cygwin", "cmd", "pipe" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
613,171
<blockquote> <p>would like to know how to pipe though</p> </blockquote> <p>You had the pipe the wrong way round, if you wanted to feed the output of ‘dir’ into Python, ‘dir’ would have to be on the left. eg.:</p> <pre><code>dir "*.*" | python -c "import sys;[sys.stdout.write('&gt;&gt;%s\n' % line) for line in sys.stdin]" </code></pre> <p>(The hack with the list comprehension is because you aren't allowed a block-introducing ‘for’ statement on one line after a semicolon.)</p> <p>Clearly the Python-native solution (‘os.listdir’) is much better in practice.</p>
2
2009-03-05T00:44:18Z
[ "python", "cygwin", "cmd", "pipe" ]
Python one-liner to print every file in the current directory
613,007
<p>How can I make the following one liner print every file through Python?</p> <pre><code>python -c "import sys;print '&gt;&gt;',sys.argv[1:]" | dir *.* </code></pre> <p>Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.</p>
1
2009-03-04T23:45:09Z
614,056
<blockquote> <p>Specifically would like to know how to pipe into a python -c</p> </blockquote> <p>see <a href="http://stackoverflow.com/questions/613007/613134#613134">cobbal's answer</a></p> <p>piping through a program is transparent from the program's point of view, all the program knows is that it's getting input from the standard input stream</p> <p>Generally speaking, a shell command of the form </p> <pre><code>A | B </code></pre> <p>redirects the output of A to be the input of B</p> <p>so if A spits "asdf" to standard output, then B gets "asdf" into its standard input</p> <p>the standard input stream in python is <a href="http://docs.python.org/library/sys.html#sys.stdin" rel="nofollow"><code>sys.stdin</code></a></p>
1
2009-03-05T09:12:06Z
[ "python", "cygwin", "cmd", "pipe" ]
Why do I get wrong results for hmac in Python but not Perl?
613,111
<p>I'm trying to compute hmac using sha-512.</p> <p>The Perl code: </p> <pre><code>use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; </code></pre> <p>and gives the correct hash of </p> <pre><code>87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 </code></pre> <p>Python version: </p> <pre><code>import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() </code></pre> <p>which gives the incorrect hash of </p> <pre><code>9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a </code></pre> <p>any ideas why the Python version is giving me the wrong hash?</p> <p>Edit:<br /> version is<br /> Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)<br /> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin </p>
2
2009-03-05T00:20:15Z
613,128
<p>Which version of Python? Strings are Unicode in Python 3. Is this a Unicode issue?</p>
0
2009-03-05T00:27:08Z
[ "python", "perl", "hash", "hmac" ]
Why do I get wrong results for hmac in Python but not Perl?
613,111
<p>I'm trying to compute hmac using sha-512.</p> <p>The Perl code: </p> <pre><code>use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; </code></pre> <p>and gives the correct hash of </p> <pre><code>87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 </code></pre> <p>Python version: </p> <pre><code>import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() </code></pre> <p>which gives the incorrect hash of </p> <pre><code>9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a </code></pre> <p>any ideas why the Python version is giving me the wrong hash?</p> <p>Edit:<br /> version is<br /> Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)<br /> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin </p>
2
2009-03-05T00:20:15Z
613,137
<p>I am unable to replicate your results here. In IDLE using Python 2.5:</p> <pre><code>Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. ... IDLE 1.2.2 &gt;&gt;&gt; import hashlib, hmac &gt;&gt;&gt; print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 </code></pre>
1
2009-03-05T00:30:30Z
[ "python", "perl", "hash", "hmac" ]
Why do I get wrong results for hmac in Python but not Perl?
613,111
<p>I'm trying to compute hmac using sha-512.</p> <p>The Perl code: </p> <pre><code>use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; </code></pre> <p>and gives the correct hash of </p> <pre><code>87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 </code></pre> <p>Python version: </p> <pre><code>import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() </code></pre> <p>which gives the incorrect hash of </p> <pre><code>9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a </code></pre> <p>any ideas why the Python version is giving me the wrong hash?</p> <p>Edit:<br /> version is<br /> Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)<br /> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin </p>
2
2009-03-05T00:20:15Z
613,189
<p>Under python 2.5.2 I get the correct hash<br /> I guess the old version was the problem</p>
0
2009-03-05T00:50:23Z
[ "python", "perl", "hash", "hmac" ]
Why do I get wrong results for hmac in Python but not Perl?
613,111
<p>I'm trying to compute hmac using sha-512.</p> <p>The Perl code: </p> <pre><code>use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; </code></pre> <p>and gives the correct hash of </p> <pre><code>87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 </code></pre> <p>Python version: </p> <pre><code>import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() </code></pre> <p>which gives the incorrect hash of </p> <pre><code>9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a </code></pre> <p>any ideas why the Python version is giving me the wrong hash?</p> <p>Edit:<br /> version is<br /> Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)<br /> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin </p>
2
2009-03-05T00:20:15Z
613,271
<p>yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. </p> <p>below run on a Penryn-based MBP...</p> <pre><code>$ **uname -a** Darwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386 dpc@lizard-wifi:~$ **which python** /usr/bin/python </code></pre> <p>Running this version installed in Leopard OS</p> <pre><code>dpc@lizard-wifi:~$ python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib, hmac &gt;&gt;&gt; print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a &gt;&gt;&gt; </code></pre> <p>And then the MacPorts version of <code>python2.5</code></p> <pre><code>$ /opt/local/bin/python2.5 Python 2.5.4 (r254:67916, Feb 3 2009, 21:40:31) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib, hmac &gt;&gt;&gt; print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 &gt;&gt;&gt; </code></pre>
9
2009-03-05T01:23:29Z
[ "python", "perl", "hash", "hmac" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
613,207
<p>Technically, dictionaries aren't sequences, and therefore can't be sorted. You can do something like</p> <pre><code>sorted(a_dictionary.values()) </code></pre> <p>assuming performance isn't a huge deal.</p> <p>UPDATE: Thanks to the commenters for pointing out that I made this way too complicated in the beginning.</p>
12
2009-03-05T00:56:12Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
613,218
<p>It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples.</p> <p>For instance,</p> <pre><code>import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) </code></pre> <p><code>sorted_x</code> will be a list of tuples sorted by the second element in each tuple. <code>dict(sorted_x) == x</code>.</p> <p>And for those wishing to sort on keys instead of values:</p> <pre><code>import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) </code></pre>
2,257
2009-03-05T00:59:34Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
613,228
<p>Dicts can't be sorted, but you can build a sorted list from them.</p> <p>A sorted list of dict values:</p> <pre><code>sorted(d.values()) </code></pre> <p>A list of (key, value) pairs, sorted by value:</p> <pre><code>from operator import itemgetter sorted(d.items(), key=itemgetter(1)) </code></pre>
114
2009-03-05T01:05:22Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
613,230
<p>Pretty much the same as Hank Gay's answer;</p> <pre> sorted([(value,key) for (key,value) in mydict.items()]) </pre>
34
2009-03-05T01:06:04Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
613,326
<p>You can create an "inverted index", also</p> <pre><code>from collections import defaultdict inverse= defaultdict( list ) for k, v in originalDict.items(): inverse[v].append( k ) </code></pre> <p>Now your inverse has the values; each value has a list of applicable keys.</p> <pre><code>for k in sorted(inverse): print k, inverse[k] </code></pre>
16
2009-03-05T01:52:18Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
2,258,273
<p>You could use:</p> <p><code>sorted(d.items(), key=lambda x: x[1])</code></p> <p>This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.</p>
365
2010-02-13T16:33:51Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
3,177,025
<p>In recent Python 2.7, we have the new <a href="http://docs.python.org/dev/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections">OrderedDict</a> type, which remembers the order in which the items were added.</p> <pre><code>&gt;&gt;&gt; d = {"third": 3, "first": 1, "fourth": 4, "second": 2} &gt;&gt;&gt; for k, v in d.items(): ... print "%s: %s" % (k, v) ... second: 2 fourth: 4 third: 3 first: 1 &gt;&gt;&gt; d {'second': 2, 'fourth': 4, 'third': 3, 'first': 1} </code></pre> <p>To make a new ordered dictionary from the original, sorting by the values:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1])) </code></pre> <p>The OrderedDict behaves like a normal dict:</p> <pre><code>&gt;&gt;&gt; for k, v in d_sorted_by_value.items(): ... print "%s: %s" % (k, v) ... first: 1 second: 2 third: 3 fourth: 4 &gt;&gt;&gt; d_sorted_by_value OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)]) </code></pre>
78
2010-07-05T02:50:41Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
3,177,911
<h2>As simple as: <code>sorted(dict1, key=dict1.get)</code></h2> <p>Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question <em><a href="http://stackoverflow.com/questions/3169051/code-golf-word-frequency-chart#3170549">Code golf: Word frequency chart</a></em>). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display list of the top words, sorted by decreasing frequency. </p> <p>If you construct a dictionary with the words as keys and the number of occurences of each word as value, simplified here as</p> <pre><code>d = defaultdict(int) for w in text.split(): d[w] += 1 </code></pre> <p>then you can get list of the words in order of frequency of use with <code>sorted(d, key=d.get)</code> - the sort iterates over the dictionary keys, using as sort-key the number of word occurrences. </p> <pre><code>for w in sorted(d, key=d.get, reverse=True): print w, d[w] </code></pre> <p>I am writing this detailed explanation to illustrate what do people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the OP was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.</p>
659
2010-07-05T08:01:16Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
4,068,769
<pre><code>from django.utils.datastructures import SortedDict def sortedDictByKey(self,data): """Sorted dictionary order by key""" sortedDict = SortedDict() if data: if isinstance(data, dict): sortedKey = sorted(data.keys()) for k in sortedKey: sortedDict[k] = data[k] return sortedDict </code></pre>
9
2010-11-01T12:16:41Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
4,215,710
<p>I had the same problem, I solved it like this:</p> <pre><code>WantedOutput = sorted(MyDict, key=lambda x : MyDict[x]) </code></pre> <p>(people who answer: "It is not possible to sort a dict" did not read the question!! In fact "I can sort on the keys, but how can I sort based on the values?" clearly means that he wants a list of the keys sorted according to the value of their values.)</p> <p>Please notice that the order is not well defined (keys with the same value will be in an arbitrary order in the output list)</p>
20
2010-11-18T14:19:57Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
5,227,519
<p>This is the code:</p> <pre><code>import operator origin_list = [ {"name": "foo", "rank": 0, "rofl": 20000}, {"name": "Silly", "rank": 15, "rofl": 1000}, {"name": "Baa", "rank": 300, "rofl": 20}, {"name": "Zoo", "rank": 10, "rofl": 200}, {"name": "Penguin", "rank": -1, "rofl": 10000} ] print "&gt;&gt; Original &gt;&gt;" for foo in origin_list: print foo print "\n&gt;&gt; Rofl sort &gt;&gt;" for foo in sorted(origin_list, key=operator.itemgetter("rofl")): print foo print "\n&gt;&gt; Rank sort &gt;&gt;" for foo in sorted(origin_list, key=operator.itemgetter("rank")): print foo </code></pre> <p>Here are the results:</p> <p><strong>Original</strong></p> <pre><code>{'name': 'foo', 'rank': 0, 'rofl': 20000} {'name': 'Silly', 'rank': 15, 'rofl': 1000} {'name': 'Baa', 'rank': 300, 'rofl': 20} {'name': 'Zoo', 'rank': 10, 'rofl': 200} {'name': 'Penguin', 'rank': -1, 'rofl': 10000} </code></pre> <p><strong>Rofl</strong></p> <pre><code>{'name': 'Baa', 'rank': 300, 'rofl': 20} {'name': 'Zoo', 'rank': 10, 'rofl': 200} {'name': 'Silly', 'rank': 15, 'rofl': 1000} {'name': 'Penguin', 'rank': -1, 'rofl': 10000} {'name': 'foo', 'rank': 0, 'rofl': 20000} </code></pre> <p><strong>Rank</strong> </p> <pre><code>{'name': 'Penguin', 'rank': -1, 'rofl': 10000} {'name': 'foo', 'rank': 0, 'rofl': 20000} {'name': 'Zoo', 'rank': 10, 'rofl': 200} {'name': 'Silly', 'rank': 15, 'rofl': 1000} {'name': 'Baa', 'rank': 300, 'rofl': 20} </code></pre>
12
2011-03-08T02:06:25Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
7,237,524
<p>It can often be very handy to use <b><a href="http://docs.python.org/library/collections.html#collections.namedtuple">namedtuple</a></b>. For example, you have a dictionary of 'name' as keys and 'score' as values and you want to sort on 'score':</p> <pre><code>import collections Player = collections.namedtuple('Player', 'score name') d = {'John':5, 'Alex':10, 'Richard': 7} </code></pre> <p>sorting with lowest score first:</p> <pre><code>worst = sorted(Player(v,k) for (k,v) in d.items()) </code></pre> <p>sorting with highest score first:</p> <pre><code>best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True) </code></pre> <p>Now you can get the name and score of, let's say the second-best player (index=1) very Pythonically like this:</p> <pre><code> player = best[1] player.name 'Richard' player.score 7 </code></pre>
38
2011-08-30T00:30:15Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
7,817,348
<p>Use <strong>ValueSortedDict</strong> from <a href="http://pypi.python.org/pypi/dicts">dicts</a>:</p> <pre><code>from dicts.sorteddict import ValueSortedDict d = {1: 2, 3: 4, 4:3, 2:1, 0:0} sorted_dict = ValueSortedDict(d) print sorted_dict.items() [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)] </code></pre>
5
2011-10-19T06:25:41Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
7,947,321
<p>Iterate through a dict and sort it by its values in descending order:</p> <pre><code>$ python --version Python 3.2.2 $ cat sort_dict_by_val_desc.py dictionary = dict(siis = 1, sana = 2, joka = 3, tuli = 4, aina = 5) for word in sorted(dictionary, key=dictionary.get, reverse=True): print(word, dictionary[word]) $ python sort_dict_by_val_desc.py aina 5 tuli 4 joka 3 sana 2 siis 1 </code></pre>
4
2011-10-30T19:42:06Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
8,148,132
<p>This works in 3.1.x:</p> <pre><code>import operator slovar_sorted=sorted(slovar.items(), key=operator.itemgetter(1), reverse=True) print(slovar_sorted) </code></pre>
4
2011-11-16T07:32:01Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
8,992,838
<p>If your values are integers, and you use Python 2.7 or newer, you can use <a href="http://docs.python.org/py3k/library/collections.html#collections.Counter"><code>collections.Counter</code></a> instead of <code>dict</code>. The <code>most_common</code> method will give you all items, sorted by the value.</p>
5
2012-01-24T19:28:36Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
11,230,132
<p>If values are numeric you may also use Counter from collections</p> <pre><code>from collections import Counter x={'hello':1,'python':5, 'world':3} c=Counter(x) print c.most_common() &gt;&gt; [('python', 5), ('world', 3), ('hello', 1)] </code></pre>
14
2012-06-27T15:43:45Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
13,208,582
<p>Using Python 3.2:</p> <pre><code>x = {"b":4, "a":3, "c":1} for i in sorted(x.values()): print(list(x.keys())[list(x.values()).index(i)]) </code></pre>
1
2012-11-03T11:07:21Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
15,310,681
<p>You can use the <a href="http://docs.python.org/2/library/collections.html#collections.Counter">collections.Counter</a>. Note, this will work for both numeric and non-numeric values.</p> <pre><code>&gt;&gt;&gt; x = {1: 2, 3: 4, 4:3, 2:1, 0:0} &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; #To sort in reverse order &gt;&gt;&gt; Counter(x).most_common() [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)] &gt;&gt;&gt; #To sort in ascending order &gt;&gt;&gt; Counter(x).most_common()[::-1] [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)] &gt;&gt;&gt; #To get a dictionary sorted by values &gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; OrderedDict(Counter(x).most_common()[::-1]) OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]) </code></pre>
17
2013-03-09T12:30:22Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
15,587,800
<p>For the sake of completeness, I am posting a solution using <a href="http://docs.python.org/2/library/heapq.html" rel="nofollow">heapq</a>. Note, this method will work for both numeric and non-numeric values</p> <pre><code>&gt;&gt;&gt; x = {1: 2, 3: 4, 4:3, 2:1, 0:0} &gt;&gt;&gt; x_items = x.items() &gt;&gt;&gt; heapq.heapify(x_items) &gt;&gt;&gt; #To sort in reverse order &gt;&gt;&gt; heapq.nlargest(len(x_items),x_items, operator.itemgetter(1)) [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)] &gt;&gt;&gt; #To sort in ascending order &gt;&gt;&gt; heapq.nsmallest(len(x_items),x_items, operator.itemgetter(1)) [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)] </code></pre>
3
2013-03-23T14:19:53Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
16,435,785
<p>I came up with this one, </p> <pre><code>import operator x = {1: 2, 3: 4, 4:3, 2:1, 0:0} sorted_x = {k[0]:k[1] for k in sorted(x.items(), key=operator.itemgetter(1))} </code></pre> <p>For Python 3.x: <code>x.items()</code> replacing <code>iteritems()</code>.</p> <pre><code>&gt;&gt;&gt; sorted_x {0: 0, 1: 2, 2: 1, 3: 4, 4: 3} </code></pre> <p>Or try with <code>collections.OrderedDict</code>!</p> <pre><code>x = {1: 2, 3: 4, 4:3, 2:1, 0:0} from collections import OrderedDict od1 = OrderedDict(sorted(x.items(), key=lambda t: t[1])) </code></pre>
2
2013-05-08T08:17:55Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
18,375,444
<p>In Python 2.7, simply do:</p> <pre class="lang-py prettyprint-override"><code>from collections import OrderedDict # regular unsorted dictionary d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) # dictionary sorted by value OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) </code></pre> <p>copy-paste from : <a href="http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes">http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes</a></p> <p>Enjoy ;-)</p>
23
2013-08-22T08:38:48Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
21,738,569
<p>This returns the list of key-value pairs in the dictionary, sorted by value from highest to lowest:</p> <pre><code>sorted(d.items(), key=lambda x: x[1], reverse=True) </code></pre> <p>For the dictionary sorted by key, use the following:</p> <pre><code>sorted(d.items(), reverse=True) </code></pre> <p>The return is a list of tuples because dictionaries themselves can't be sorted.</p> <p>This can be both printed or sent into further computation.</p>
6
2014-02-12T20:10:46Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
21,767,696
<pre><code>months = {"January": 31, "February": 28, "March": 31, "April": 30, "May": 31, "June": 30, "July": 31, "August": 31, "September": 30, "October": 31, "November": 30, "December": 31} def mykey(t): """ Customize your sorting logic using this function. The parameter to this function is a tuple. Comment/uncomment the return statements to test different logics. """ return t[1] # sort by number of days in the month #return t[1], t[0] # sort by number of days, then by month name #return len(t[0]) # sort by length of month name #return t[0][-1] # sort by last character of month name # Since a dictionary can't be sorted by value, what you can do is to convert # it into a list of tuples with tuple length 2. # You can then do custom sorts by passing your own function to sorted(). months_as_list = sorted(months.items(), key=mykey, reverse=False) for month in months_as_list: print month </code></pre>
2
2014-02-13T23:18:20Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
21,784,867
<pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; x = {1: 2, 3: 4, 4:3, 2:1, 0:0} &gt;&gt;&gt; sorted_x = collections.OrderedDict(sorted(x.items(), key=lambda t:t[1])) &gt;&gt;&gt; OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]) </code></pre> <p><code>OrderedDict</code> is subclass of <code>dict</code></p>
0
2014-02-14T16:44:34Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
22,150,003
<p>Because of requirements to retain backward compatability with older versions of <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a> I think the OrderedDict solution is very unwise. You want something that works with Python 2.7 and older versions.</p> <p>But the collections solution mentioned in another answer is absolutely superb, because you retrain a connection between the key and value which in the case of dictionaries is extremely important.</p> <p>I don't agree with the number one choice presented in another answer, because it throws away the keys.</p> <p>I used the solution mentioned above (code shown below) and retained access to both keys and values and in my case the ordering was on the values, but the importance was the ordering of the keys after ordering the values.</p> <pre><code>from collections import Counter x = {'hello':1, 'python':5, 'world':3} c=Counter(x) print c.most_common() &gt;&gt; [('python', 5), ('world', 3), ('hello', 1)] </code></pre>
0
2014-03-03T14:58:30Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
22,903,797
<p>Why not try this approach. Let us define a dictionary called mydict with the following data:</p> <pre><code>mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} </code></pre> <p>If one wanted to sort the dictionary by keys, one could do something like:</p> <pre><code>for key in sorted(mydict.iterkeys()): print "%s: %s" % (key, mydict[key]) </code></pre> <p>This should return the following output:</p> <pre><code>alan: 2 bob: 1 carl: 40 danny: 3 </code></pre> <p>On the other hand, if one wanted to sort a dictionary by value (as is asked in the question), one could do the following:</p> <pre><code>for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)): print "%s: %s" % (key, value) </code></pre> <p>The result of this command (sorting the dictionary by value) should return the following:</p> <pre><code>bob: 1 alan: 2 danny: 3 carl: 40 </code></pre>
9
2014-04-07T04:46:44Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
26,049,456
<p>You can use a <a href="https://pypi.python.org/pypi/skipdict/1.0">skip dict</a> which is a dictionary that's permanently sorted by value.</p> <pre><code>&gt;&gt;&gt; data = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} &gt;&gt;&gt; SkipDict(data) {0: 0.0, 2: 1.0, 1: 2.0, 4: 3.0, 3: 4.0} </code></pre> <p>If you use <code>keys()</code>, <code>values()</code> or <code>items()</code> then you'll iterate in sorted order by value.</p> <p>It's implemented using the <a href="http://en.wikipedia.org/wiki/Skip_list">skip list</a> datastructure.</p>
9
2014-09-25T22:56:55Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
27,064,308
<p>You can use the sorted function of Python</p> <p><code>sorted(iterable[, cmp[, key[, reverse]]])</code></p> <p>Thus you can use:</p> <p><code>sorted(dictionary.items(),key = lambda x :x[1])</code></p> <p>Visit this link for more information on sorted function: <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow">https://docs.python.org/2/library/functions.html#sorted</a></p>
4
2014-11-21T15:04:09Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
30,949,456
<p>Here is a solution using zip on <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><code>d.values()</code> and <code>d.keys()</code></a>. A few lines down this link (on Dictionary view objects) is:</p> <blockquote> <p>This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()).</p> </blockquote> <p>So we can do the following:</p> <pre><code>d = {'key1': 874.7, 'key2': 5, 'key3': 8.1} d_sorted = sorted(zip(d.values(), d.keys())) print d_sorted # prints: [(5, 'key2'), (8.1, 'key3'), (874.7, 'key1')] </code></pre>
3
2015-06-20T01:44:58Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
31,689,638
<p>I've found that the following function performs well compared to other solutions posted, even on large dictionaries.</p> <pre><code>vsort = lambda d: sorted(d.iteritems(), key=lambda (k, v): v) </code></pre> <p>Example:</p> <pre><code>data = {} for i in range(10): data[i] = i if i % 2 else -i print 'Original' for k, v in data.items(): print "k: %s v: %s" % (k, v) print '' print 'Value-sorted' for k, v in vsort(data): print "k: %s v: %s" % (k, v) print '' </code></pre> <p>Output:</p> <pre><code>Original k: 0 v: 0 k: 1 v: 1 k: 2 v: -2 k: 3 v: 3 k: 4 v: -4 k: 5 v: 5 k: 6 v: -6 k: 7 v: 7 k: 8 v: -8 k: 9 v: 9 Value-sorted k: 8 v: -8 k: 6 v: -6 k: 4 v: -4 k: 2 v: -2 k: 0 v: 0 k: 1 v: 1 k: 3 v: 3 k: 5 v: 5 k: 7 v: 7 k: 9 v: 9 </code></pre> <p>Sample timing code:</p> <pre><code>import numpy as np from time import time import operator np.random.seed(0) N = int(1e6) x = {i: np.random.random() for i in xrange(N)} t0 = -time() sorted_0 = sorted(x.items(), key=operator.itemgetter(1)) t0 += time() t1 = -time() sorted_1 = vsort(x) t1 += time() print 'operator-sort: %f vsort: %f' % (t0, t1) print sorted_0[:3] print sorted_1[:3] </code></pre> <p>Output:</p> <pre><code>operator-sort: 2.041510 vsort: 1.692324 [(661553, 7.071203171893359e-07), (529124, 1.333679640169727e-06), (263972, 2.9504162779581122e-06)] [(661553, 7.071203171893359e-07), (529124, 1.333679640169727e-06), (263972, 2.9504162779581122e-06)] </code></pre>
-3
2015-07-29T01:08:13Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
31,741,215
<p>Of course, remember, you need to use <code>OrderedDict</code> because regular Python dictionaries don't keep the original order. </p> <pre><code>from collections import OrderedDict a = OrderedDict(sorted(originalDict.items(), key = lambda x: x[1])) </code></pre> <hr> <p>If you do not have Python 2.7 or higher, the best you can do is iterate over the values in a generator function. (There is an OrderedDict for 2.4 and 2.6 <a href="https://pypi.python.org/pypi/ordereddict" rel="nofollow">here</a>, but </p> <pre><code>a) I don't know about how well it works </code></pre> <p>and </p> <pre><code>b) You have to download and install it of course. If you do not have administrative access, then I'm afraid the option's out.) </code></pre> <hr> <pre><code>def gen(originalDict): for x,y in sorted(zip(originalDict.keys(), originalDict.values()), key = lambda z: z[1]): yield (x, y) #Yields as a tuple with (key, value). You can iterate with conditional clauses to get what you want. for bleh, meh in gen(myDict): if bleh == "foo": print(myDict[bleh]) </code></pre> <hr> <p>You can also print out every value</p> <pre><code>for bleh, meh in gen(myDict): print(bleh,meh) </code></pre> <p>Please remember to remove the parentheses after print if not using Python 3.0 or above</p>
2
2015-07-31T08:08:49Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
34,103,440
<p><strong>UPDATE: 5 DECEMBER 2015 using Python 3.5</strong></p> <p>Whilst I found the accepted answer useful, I was also surprised that it hasn't been updated to reference <strong><a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict">OrderedDict</a></strong> from the standard library <strong>collections</strong> module as a viable, modern alternative - designed to solve exactly this type of problem.</p> <pre><code>from operator import itemgetter from collections import OrderedDict x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = OrderedDict(sorted(x.items(), key=itemgetter(1))) # OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]) </code></pre> <p>The official <strong><a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict">OrderedDict</a></strong> documentation offers a very similar example too, but using a lambda for the sort function:</p> <pre><code># regular unsorted dictionary d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted by value OrderedDict(sorted(d.items(), key=lambda t: t[1])) # OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) </code></pre>
29
2015-12-05T09:46:06Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
34,995,529
<pre><code>&gt;&gt;&gt; e = {1:39, 4:34, 7:110, 2:87} &gt;&gt;&gt; sortE = sorted(e.items(), key=lambda value: value[1]) &gt;&gt;&gt; print(sortE) [(4, 34), (1, 39), (2, 87), (7, 110)] </code></pre> <p>You can use a lambda function to sort things up by value and store them processed inside a variable, in this case <strong>sortE</strong> with <strong>e</strong> the original dictionary.</p>
13
2016-01-25T14:54:43Z
[ "python", "sorting", "dictionary" ]
Sort a Python dictionary by value
613,183
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
1,837
2009-03-05T00:49:05Z
39,424,969
<h1>As of <a href="https://docs.python.org/3.6/whatsnew/3.6.html" rel="nofollow">Python 3.6</a> the builtin dict will be ordered</h1> <p>Good news, so the OP's original use case of mapping pairs retrieved from a database with unique string ids as keys and numeric values as values into a builtin python v3.6+ dict, should now respect the insert order.</p> <p>If say the resulting 2 column table expression from a database query like:</p> <pre><code>SELECT a_key, a_value FROM a_table ORDER BY a_value; </code></pre> <p>would be stored in two python tuples k_seq and v_seq (aligned by numerical index and with the same length of course), then:</p> <pre><code>k_seq = ('foo', 'bar', 'baz') v_seq = (0, 1, 42) ordered_map = dict(zip(k_seq, v_seq)) </code></pre> <p>Allow to output later as:</p> <pre><code>for k, v in ordered_map.items(): print(k, v) </code></pre> <p>yielding in this case (for the new python 3.6+ builtin dict!):</p> <pre><code>foo 0 bar 1 baz 42 </code></pre> <p>in the same ordering per value of v.</p> <p>Where in the python 3.5 install on my machine it currently yields:</p> <pre><code>bar 1 foo 0 baz 42 </code></pre> <h2>Details:</h2> <p>As proposed in 2012 by Raymond Hettinger (cf. Mail on python-dev with subject <a href="https://mail.python.org/pipermail/python-dev/2012-December/123028.html" rel="nofollow">"More compact dictionaries with faster iteration"</a>) and now (in 2016) announced in a mail by Victor Stinner to python-dev with subject <a href="https://mail.python.org/pipermail/python-dev/2016-September/146327.html" rel="nofollow">"Python 3.6 dict becomes compact and gets a private version; and keywords become ordered"</a> due to the fix/implementation of issue 27350 <a href="http://bugs.python.org/issue27350" rel="nofollow">"Compact and ordered dict"</a> in Python 3.6 we will now be able, to use a built-in dict to maintain insert order! !</p> <p>Maybe on a meta level python, this will lead to:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'OrderedDict' </code></pre> <p>for some later python versions ... ;-)</p> <p>And maybe quite some stackoverflow high decorated question and answer pages will receive variants of this info and many high quality answers will require a per version update too.</p> <h3>Caveat Emptor:</h3> <p>As @ajcr rightfully notes: "The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon." (from the <a href="https://docs.python.org/3.6/whatsnew/3.6.html" rel="nofollow">whatsnew36</a>) not nit picking, <strong>but</strong> the citation was cut a bit pessimistic ;-). It continues as " (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5)."</p> <p>So as in some human languages (e.g. German), usage shapes the language, and the will now has been declared ... in <a href="https://docs.python.org/3.6/whatsnew/3.6.html" rel="nofollow">whatsnew36</a></p>
1
2016-09-10T10:05:36Z
[ "python", "sorting", "dictionary" ]
How does Vista Recycle bin work?
613,246
<p>I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC. </p> <p>Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).</p>
5
2009-03-05T01:12:38Z
613,258
<p>You should use the <a href="http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx" rel="nofollow"><code>SHFileOperation</code></a> function or, on Vista, the <a href="http://msdn.microsoft.com/en-us/library/bb775771(VS.85).aspx" rel="nofollow"><code>IFileOperation</code></a> interface (as pointed out by gix below).</p> <p>From the remarks on <code>SHFileOperation</code>:</p> <blockquote> <p>When used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the fFlags member of the SHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the Recycle Bin. If you want to simply delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.</p> </blockquote>
5
2009-03-05T01:17:39Z
[ "python", "windows-vista", "recycle-bin" ]
How does Vista Recycle bin work?
613,246
<p>I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC. </p> <p>Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).</p>
5
2009-03-05T01:12:38Z
613,260
<p>It looks like <a href="http://mail.python.org/pipermail/python-list/2001-June/091800.html" rel="nofollow">this mailing list entry</a> might help you.</p>
-1
2009-03-05T01:18:39Z
[ "python", "windows-vista", "recycle-bin" ]
How does Vista Recycle bin work?
613,246
<p>I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC. </p> <p>Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).</p>
5
2009-03-05T01:12:38Z
613,267
<p>Moving files to Windows' Recycle Bin is a Shell operation. Shell operations are run via COM. For older Windows versions there is the <a href="http://msdn.microsoft.com/en-us/library/bb762164%28VS.85%29.aspx" rel="nofollow">SHFileOperation interface</a>. Since Vista there is the new <a href="http://msdn.microsoft.com/en-us/library/bb775771%28VS.85%29.aspx" rel="nofollow">IFileOperation interface.</a></p>
5
2009-03-05T01:20:37Z
[ "python", "windows-vista", "recycle-bin" ]
How does Vista Recycle bin work?
613,246
<p>I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC. </p> <p>Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).</p>
5
2009-03-05T01:12:38Z
3,039,820
<p>I have written a <a href="http://pypi.python.org/pypi/Send2Trash/" rel="nofollow">Python library that does precisely that</a>. You might want to check it out.</p>
3
2010-06-14T18:28:15Z
[ "python", "windows-vista", "recycle-bin" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
613,368
<p>It seems like the ideal of "Pythonic" code serves a lot of the same purpose as <code>use strict</code>.</p>
-2
2009-03-05T02:11:37Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
613,435
<p>Python does have something that can change script syntax:</p> <pre><code>from __future__ import print_function </code></pre> <p>and various other future-features that have syntax implications. It's just that Python's syntax has been stricter, stabler and more well-defined than historical Perl; the kind of things that ‘strict refs’ and ‘strict subs’ prohibit have never existed in Python.</p> <p>‘strict vars’ is primarily intended to stop typoed references and missed-out ‘my’s from creating accidental globals (well, package variables in Perl terms). This can't happen in Python as bare assignments default to local declaration, and bare unassigned symbols result in an exception.</p> <p>(There is still the case where users accidentally try to write-through to a global without declaring it with a ‘global’ statement, causing either an accidental local or, more often, an UnboundLocalError. This tends to be learned fairly quickly, but it is an arguable case where having to declare your locals could help. Although few experienced Python programmers would accept the readability burden.)</p> <p>Other language and library changes that do not involve syntax are handled through the <a href="http://docs.python.org/library/warnings.html">warnings</a> system.</p>
10
2009-03-05T02:54:53Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
613,439
<p>I consider the <code>'use strict'</code> in Perl more like a pragma as you hinted at: it changes the behavior of the compiler. </p> <p>Perl language philosophy is different from python philosophy. As in, you are given more than enough rope to hang yourself repeatedly, in Perl. </p> <p>Larry Wall is big into linguistics, so we have from Perl what is referred to as the TIMTOWTDI (say <code>tim-toe-dee</code>) principle vs. Zen of python:</p> <blockquote> <p>There should be one-- and preferably only one --obvious way to do it.</p> </blockquote> <p>you could very easily use pylint and PyChecker to come up with your own flavor of <code>use strict</code> for python (or something analogous to <code>perl -cw *scriptname*</code>) but because of the different philosophies in the language design, you will not encounter this in practice widely.</p> <p>Based on your comment to the first poster, you are familiar with python's <code>import this</code>. There are a lot of things in there which illuminate why you do not see an equivalent of <code>use strict</code> in Python. If you meditate on the <em>koan</em> found in the Zen of Python, you may find enlightenment for yourself. :)</p>
3
2009-03-05T02:57:31Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
613,492
<p>I don't have a Perl background, but from what I know, there's no feature in python that needs to be disabled in order for your code to be "more reliable", so in that sense, I guess you can say it's unnecessary</p>
-3
2009-03-05T03:31:28Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
613,499
<p>"the run-time binding philosophy that Python embraces... makes "use strict" behavior unnecessary [and] especially undesirable"</p> <p>Pretty good summary. Thanks.</p> <p>That is essentially it. Static analysis tools don't help Python enough to be worthwhile. </p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"I'm asking for us to introspect on <em>why</em> we don't need it and, relatedly, why Perl programmers think they do need it."</p> <p>The reason why is precisely the reason you already gave. We don't need it because it doesn't help. Clearly, you don't like that answer, but there's not much more to be said. Compile-time or pre-compile time checking simply does not help. </p> <p>However, since you took the time to asked the question again, I'll provide more evidence for the answer you already gave.</p> <p>I write Java almost as much as I write Python. Java's static type checking does not prevent any logic problems; it doesn't facilitate meeting performance requirements; it doesn't help meet the use cases. It doesn't even reduce the volume of unit testing.</p> <p>While static type checking does spot the occasional misuse of a method, you find this out just as quickly in Python. In Python you find it at unit test time because it won't run. Note: I'm not saying wrong types are found with lots of clever unit tests, I'm saying most wrong type issues are found through unhandled exceptions where the thing simply won't run far enough to get to test assertions.</p> <p>The reason why is Pythonistas don't waste time on static checking is simple. We don't need it. It doesn't offer any value. It's a level of analysis that has no economic benefit. It doesn't make me any more able to solve the real problems that real people are having with their real data.</p> <p>Look at the most popular SO Python questions that are language (not problem domain or library) related.</p> <p><a href="http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none">http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none</a> -- <code>==</code> vs. <code>is</code>. No static checking can help with this. Also, see <a href="http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python">http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python</a></p> <p><a href="http://stackoverflow.com/questions/36901/what-does-and-do-for-python-parameters">http://stackoverflow.com/questions/36901/what-does-and-do-for-python-parameters</a> -- <code>*x</code> gives a list, <code>**x</code> gives a dictionary. If you don't know this, your program dies immediately when you try to do something inappropriate for those types. "What if your program never does anything 'inappropriate'". Then your program works. 'nuff said.</p> <p><a href="http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python">http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python</a> -- this is a plea for some kind of limited-domain type. A class with class-level values pretty much does that job. "What if someone changes the assignment". Easy to build. Override <code>__set__</code> to raise an exception. Yes static checking might spot this. No, it doesn't happen in practice that someone gets confused about an enum constant and a variable; and when they do, it's easy to spot at run time. "What if the logic never gets executed". Well, that's poor design and poor unit testing. Throwing a compiler error and putting in wrong logic that's never tested is no better than what happens in a dynamic language when it's never tested.</p> <p><a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">http://stackoverflow.com/questions/47789/generator-expressions-vs-list-compre
11
2009-03-05T03:36:24Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
614,565
<p>Python has no true lexical scoping, so strict vars wouldn't be very sensible. It has no symbolic references AFAIK, so it has not need for strict refs. It has not barewords, so it has no need for strict vars.</p> <p>To be honest, it's only lexical scoping I miss. The other two I'd consider warts in Perl.</p>
5
2009-03-05T12:25:19Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
614,570
<p>I think there's some confusion as the what "use strict" does, from the comments I'm seeing. It does not turn on compile time type checks (to be like Java). In that sense, Perl progammers are in agreement with python programmers. As S.Lott says above these types of checks don't protect against logic bugs, don't reduce the number of unit tests you need to write and we're also not big fans of bondage programming.</p> <p>Here's a list of what "use strict" does do:</p> <ol> <li><p>Using symbolic references is a run-time error. This prevents you from doing crazy (but sometimes useful things like)</p> <p><code>$var = 'foo';</code></p> <p><code>$foo = 'bar';</code></p> <p><code>print $$var; # this would contain the contents of $foo unless run under strict</code></p></li> <li><p>Using undeclared variables is a run-time error (this means you need to use "my", "our" or "local" to declare your variable's scope before using it.</p></li> <li><p>All barewords are considered compile-time syntax errors. Barewords are words that have not been declared as symbols or subroutines. This is mainly to outlaw something that was historically done but is considered to have been a mistake.</p></li> </ol>
7
2009-03-05T12:27:03Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
615,306
<p>Well, I'm not much of a python programmer, but I'd say that the answer is 'YES'.</p> <p>Any dynamic language that lets you create a variable with any name at any time, could use a 'strict' pragma.</p> <p>Strict vars (one of the options for strict in Perl, 'use strict' turns them all on at once) in Perl requires that all variables are declared before they are used. Which means that this code:</p> <pre><code>my $strict_is_good = 'foo'; $strict_iS_good .= 'COMPILE TIME FATAL ERROR'; </code></pre> <p>Generates a fatal error at compile time.</p> <p>I don't know of a way to get Python to reject this code at compile time:</p> <pre><code>strict_is_good = 'foo'; strict_iS_good += 'RUN TIME FATAL ERROR'; </code></pre> <p>You will get a run-time exception that <code>strict_iS_good</code> is undefined. But only when the code is executed. If your test suite does not have 100% coverage, you can easily ship this bug.</p> <p>Any time I work in a language that does not have this behavior (PHP for example), I get nervous. I am not a perfect typist. A simple, but hard to spot, typo can cause your code to fail in ways that may be hard to track down. </p> <p>So, to reiterate, <strong>YES</strong> Python could use a 'strict' pragma to turn on compile time checks for things that can be checked at compile time. I can't think of any other checks to add, but a better Python programmer probably could think of some. </p> <p><b>Note</b> I focus on the pragmatic effect of stict vars in Perl, and am glossing over some of the details. If you really want to know all the details see <a href="http://perldoc.perl.org/strict.html">the perldoc for strict</a>.</p> <p><strong>Update: Responses to some comments</strong></p> <p><em>Jason Baker</em> : Static checkers like pylint are useful. But they represent an extra step that can be and often is skipped. Building some basic checks into the compiler guarantees that these checks are performed consistently. If these checks are controllable by a pragma, even the objection relating to the cost of the checks becomes moot. </p> <p><em>popcnt</em> : I know that python will generate a run time exception. I said as much. I advocate compile time checking where possible. Please reread the post.</p> <p><em>mpeters</em> : No computer analysis of code can find all errors--this amounts to solving the halting problem. Worse, to find typos in assignments, your compiler would need to know your <em>intentions</em> and find places where your intentions differ from your code. This is pretty clearly impossible.</p> <p>However this does not mean that no checking should be done. If there are classes of problems that are easy to detect, then it makes sense to trap them.</p> <p>I'm not familiar enough with pylint and pychecker to say what classes of errors they will catch. As I said I am very inexperienced with python.</p> <p>These static analysis programs are useful. However, I believe that unless they duplicate the capabilities of the compiler, the compiler will always be in a position to "know" more about the program than any static checker could. It seems wasteful not to take advantage of this to reduce errors where possible.</p> <p><strong>Update 2:</strong></p> <p>cdleary - In theory, I agree with you, a static analyzer can do any validation that the compiler can. And in the case of Python, it should be enough. </p> <p>However, if your compiler is complex enough (especially if you have lots of pragmas that change how compilation occurs, or if like Perl, you can run code at compile time), then the static analyzer must approach the complexity of the compiler/interpreter to do the analysis. </p> <p>Heh, all this talk of complex compilers and running code at compile time shows my Perl background.</p> <p>My understanding is that Python does not have pragmas and can not run arbitrary code at compile time. So, unless I am wrong or these features are added, a relatively simple parser in the static analyzer should suffice. It certainly would be helpful to force these checks at every execution. Of course, the way I'd do this is with a pragma.</p> <p>Once you add pragmas to the mix, you have started down a slippery slope and the complexity of you analyzer must grow in proportion to the power and flexibility you provide in your pragmas. If you are not careful, you can wind up like Perl, and then "only python can parse Python," a future I wouldn't want to see.</p> <p>Maybe a command line switch would be a better way to add forced static analysis ;)</p> <p>(In no way do intend to impugn Python's capabilities when I say that it can't futz with compile time behavior like Perl can. I have a hunch that this is a carefully considered design decision, and I can see the wisdom in it. Perl's extreme flexibility at compile time is, IMHO, a great strength and a terrible weakness of the language; I see the wisdom in this approach as well.)</p>
32
2009-03-05T15:37:14Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
616,256
<p>I've found that I only really care about detecting references to undeclared vars. Eclipse has pylint integration via PyDev and, although pylint is far from perfect, it does a reasonable job at that.</p> <p>It does kind of go against Python's dynamic nature, and I do have to add #IGNOREs occasionally, when my code gets clever about something. But I find that happens infrequently enough that I'm happy with it.</p> <p>But I could see the utility of some pylint-like functionality becoming available in the form of a command-line flag. Kind of like Python 2.6's -3 switch, which identifies points of incompatibility between Python 2.x and 3.x code.</p>
1
2009-03-05T19:25:17Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
4,140,155
<p>This original answer is correct, but does not perhaps explain the situation in a practical sense.</p> <blockquote> <p>There exist static analysis tools for Python, but compile time checks tend to be >diametrically opposed to the run-time binding philosophy that Python embraces.</p> </blockquote> <p>What 'use strict' provides in Perl is the ability to ensure that a mis-spelled or variable name is (usually) caught at compile-time. This does improve code reliability, and speeds up development. But in order to make such a thing worthwhile, you need to declare variables. And Python style seems to discourage that.</p> <p>So in Python, you never find out about a mis-spelled variable until you notice at run-time that the assignment you thought you made is not being made, or that an expression seems to resolve to an unexpected value. Catching such errors can be time-consuming, especially as programs get large, and as people are forced to maintain code developed by others.</p> <p>Java and C/C++ take it a step further, with type checking. The motivation is practical, rather than philosophical. How can you catch as many errors as possible as soon as possible, and be sure that you eliminate all of them before releasing code to production? Each language seems to take a particular strategy and run with it, based upon what they think is important. In a language like Perl, where run-time binding isn't supported, it makes sense to take advantage of 'use strict' to make development easier.</p>
3
2010-11-10T00:28:43Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
6,740,746
<p>It is very difficult to write large programs without 'use strict' in Perl. Without 'use strict', if you use a variable again, and misspell it by leaving a letter out, the program still runs. And without test cases to check your results, you can never find such errors. It can be very time-consuming to find why you are getting wrong results due to this reason.</p> <p>Some of my Perl programs consist of 5,000 lines to 10,000 lines of code broken into dozens of modules. One cannot really do production programming without 'use strict'. I would never allow production code to be installed in the factory with languages that do not enforce "variable declarations".</p> <p>This is why Perl 5.12.x now has the 'use strict' as the default behavior. You can turn them off.</p> <p>PHP has given me quite a few problems because of no variable declaration enforcement. So you need to limit yourself to small programs with this language.</p> <p>Just an opinion ...</p> <p>abcParsing</p>
1
2011-07-18T23:44:44Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Is there a need for a "use strict" Python compiler?
613,364
<p>There exist <a href="http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python">static analysis tools for Python</a>, but compile time checks tend to be diametrically opposed to the <a href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">run-time binding philosophy</a> that Python embraces. It's <em>possible</em> to wrap the standard Python interpreter with a static analysis tool to enforce some "<a href="http://perldoc.perl.org/strict.html">use strict</a>"-like constraints, but we don't see any widespread adoption of such a thing.</p> <p>Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?</p> <p>Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?</p> <p>Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you <em>can</em> write Perl without "use strict," but (from what I've seen) most Perl programmers <em>do</em> use it.</p> <p>Note: The Python interpreter-wrapper need not <em>require</em> "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.</p> <p><hr /></p> <p>Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)</p> <p>The "use strict" directive has three distinct components, only two of which are really interesting:</p> <ul> <li><p>use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only <code>global</code> scope and <code>local</code> scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.</p> <pre><code>FOO = 12 foo += 3 </code></pre> <p>If you're not doing anything fancy with your namespaces this can be useful to check for typos.</p></li> <li><p>use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using <code>locals()</code> and <code>globals()</code> to do symbolic binding and identifier lookup.</p></li> <li><p>use strict subs: No real analog in Python.</p></li> </ul>
28
2009-03-05T02:08:25Z
25,151,630
<p>Perl is a unrestrained language as they said :) . So you can use the variable before announced ; Eg : If you use a var name "is_array" but type in "is_arrby" ,the compiler won't report error without "use strict" . So when coding long program in perl ,better use "use strict" statement. Of course, less than 50 lines for running one time script, there is no need :) </p>
0
2014-08-06T03:10:24Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,473
<p>Whenever I wanted to do this, I would just scrape <a href="http://whatismyip.org" rel="nofollow">whatismyip.org</a>. When you go to the site, it gives you your plain text public IP. Plain and simple.</p> <p>Just have your script access that site and read the IP.</p> <p>I don't know if you were implying this in your post or not, but it isn't possible to get your public IP from your own computer. It has to come from an external source.</p> <p><strong>2013 edit: This site returns an image now instead of text, so it's useless for this purpose.</strong></p>
8
2009-03-05T03:20:57Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,477
<p>Your simplest way may be to ask some server on the outside of your network.</p> <p>One thing to keep in mind is that different destinations may see a different address for you. The router may be multihomed. And really that's just where problems begin.</p>
3
2009-03-05T03:22:34Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,482
<p>I have made a program that connects to <a href="http://automation.whatismyip.com/n09230945.asp" rel="nofollow">http://automation.whatismyip.com/n09230945.asp</a> it is is written in D an getting someone else to tell you what they see your ip as is probably the most reliable way:</p> <pre><code>/* Get my IP address */ import tango.net.http.HttpGet; import tango.io.Stdout; void main() { try { auto page = new HttpGet ("http://automation.whatismyip.com/n09230945.asp"); Stdout(cast(char[])page.read); } catch(Exception ex) { Stdout("An exception occurred"); } } </code></pre> <p>Edit python code should be like:</p> <pre><code>from urllib import urlopen print urlopen('http://automation.whatismyip.com/n09230945.asp').read() </code></pre>
17
2009-03-05T03:26:16Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,518
<p>If the network has an UpNp server running on the gateway you are able to talk to the gateway and ask it for your outside IP address.</p>
3
2009-03-05T03:52:25Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,565
<p>Targeting www.whatsmyip.org is rude. They plea not to do that on the page.</p> <p>Only a system on the same level of NAT as your target will see the same IP. For instance, your application may be behind multiple layers of NAT (this happens more as you move away from the US, where the glut of IPs are).</p> <p>STUN is indeed the best method. In general, you should be planning to run a (STUN) server somewhere that you application can ask: do not hard code other people's servers. You have to code to send some specific messages as described in rfc5389.</p> <p>I suggest a good read of, and related links. <a href="http://www.ietf.org/html.charters/behave-charter.html">http://www.ietf.org/html.charters/behave-charter.html</a></p> <p>You may prefer to look at IPv6, and Teredo to make sure that you always have IPv6 access. (Microsoft Vista makes this very easy, I'm told)</p>
10
2009-03-05T04:30:19Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
613,600
<p>This may be the easiest way. Parse the output of the following commands:</p> <ol> <li>run a traceroute to find a router that is less than 3 hops out from your machine.</li> <li>run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one.</li> </ol> <p>For example, I am on a Windows machine, but the same idea should work from unix too.</p> <pre><code>&gt; tracert -d www.yahoo.com Tracing route to www-real.wa1.b.yahoo.com [69.147.76.15] over a maximum of 30 hops: 1 &lt;1 ms &lt;1 ms &lt;1 ms 192.168.14.203 2 * * * Request timed out. 3 8 ms 8 ms 9 ms 68.85.228.121 4 8 ms 8 ms 9 ms 68.86.165.234 5 10 ms 9 ms 9 ms 68.86.165.237 6 11 ms 10 ms 10 ms 68.86.165.242 </code></pre> <p>The 68.85.228.121 is a Comcast (my provider) router. We can ping that:</p> <pre><code>&gt; ping -r 9 68.85.228.121 -n 1 Pinging 68.85.228.121 with 32 bytes of data: Reply from 68.85.228.121: bytes=32 time=10ms TTL=253 Route: 66.176.38.51 -&gt; 68.85.228.121 -&gt; 68.85.228.121 -&gt; 192.168.14.203 </code></pre> <p>Voila! The 66.176.38.51 is my public IP.</p>
20
2009-03-05T04:47:07Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
628,180
<p>As mentioned by several people, <a href="http://en.wikipedia.org/wiki/STUN" rel="nofollow">STUN</a> is indeed the proper solution.</p> <ul> <li>a list of <a href="http://www.voip-info.org/wiki-STUN" rel="nofollow">public STUN servers</a></li> <li>a free software <a href="http://sourceforge.net/projects/stun/" rel="nofollow">STUN client</a></li> <li>The <a href="http://www.ietf.org/rfc/rfc5389.txt" rel="nofollow">STUN standard</a></li> </ul>
3
2009-03-09T21:54:33Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
5,199,330
<p>another cheeky way: if your router has got the option to update it's web IP on <a href="http://dyn.com/dns/" rel="nofollow">DynDNS</a>, you can get your own IP with something like:</p> <pre><code>IP=`resolveip -s myalias.dyndns-home.com` </code></pre>
1
2011-03-04T21:13:42Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
16,698,596
<p><strong>EDIT</strong>: curlmyip.com is no longer available. (thanks maxywb)</p> <p><strong>Original Post</strong>:</p> <p>As of writing this post, curlmyip.com works. From the command line:</p> <pre><code>curl curlmyip.com </code></pre> <p>It's a third-party website, which may or may not be available a couple years down the road. But for the time being, it seems pretty simple and to the point.</p>
8
2013-05-22T17:57:52Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
22,075,729
<p>To get your external ip, you could make a dns query to an opendns server with the special hostname "myip.opendns.com":</p> <pre><code>from subprocess import check_output ip = check_output(["dig", "+short", "@resolver1.opendns.com", "myip.opendns.com"]).decode().strip() </code></pre> <p>On Windows, you could try <code>nslookup</code>.</p> <p>There is no dns module in Python stdlib that would allow to specify custom dns server. You could use third party libraries e.g., <a href="https://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> to make the dns query:</p> <pre><code>from twisted.internet import task # $ pip install twisted from twisted.names.client import Resolver from twisted.python.util import println def main(reactor): opendns_resolvers = [("208.67.222.222", 53), ("208.67.220.220", 53)] resolver = Resolver(servers=opendns_resolvers, reactor=reactor) # use magical hostname to get our public ip return resolver.getHostByName('myip.opendns.com').addCallback(println) task.react(main) </code></pre> <p>Here's the same using <a href="http://www.dnspython.org/" rel="nofollow"><code>dnspython</code> library</a>:</p> <pre><code>import dns.resolver # $ pip install dnspython resolver = dns.resolver.Resolver(configure=False) resolver.nameservers = ["208.67.222.222", "208.67.220.220"] print(resolver.query('myip.opendns.com')[0]) </code></pre>
3
2014-02-27T17:22:34Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
33,743,758
<p>Duck Duck Go gives free access to their API according to their own page here: <a href="https://duckduckgo.com/api" rel="nofollow">https://duckduckgo.com/api</a></p> <p>Here's the URL you hit if you want your IP address: <a href="http://api.duckduckgo.com/?q=my+ip&amp;format=json" rel="nofollow">http://api.duckduckgo.com/?q=my+ip&amp;format=json</a></p> <p>That returns a JSON object. The <code>Answer</code> attribute has a human readable string with your ip address in it. Example:</p> <pre><code>{ ... "Answer": "Your IP address is ww.xx.yyy.zzz in &lt;a href=\"http://open.mapquest.com/?q=aaaaa(bbbbb)\"&gt;aaaaa(bbbbb)&lt;/a&gt;" ... } </code></pre> <p>You could extract the ip address from that string by using <code>split()[4]</code>, if you think that it's a safe assumption that this string won't ever change or you're willing to need to periodically fix it.</p> <p>Alternatively, if you want to have a more future proof method, you could loop over everything returned by <code>split()</code> and return the first item that is an ip address. See here for validating IP addresses: <a href="http://stackoverflow.com/q/319279/901641">How to validate IP address in Python?</a></p>
0
2015-11-16T20:10:49Z
[ "python", "ip-address", "tcp" ]
Discovering public IP programatically
613,471
<p>I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)</p> <p>Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?</p> <p>P.S. I'm planning on writing a short python script to do it</p>
23
2009-03-05T03:18:42Z
35,317,247
<p>I like the <a href="https://ipify.org" rel="nofollow">ipify.org</a>:</p> <ul> <li>it's free to use (even programmatically and even heavy traffic)</li> <li>response contains only the IP address without any garbage (no need for parsing)</li> <li>you can also request response in JSON</li> <li>works for both IPv4 and IPv6</li> <li>it's hosted in cloud</li> <li>it's open source</li> </ul> <pre><code>$ curl api.ipify.org 167.220.196.42 $ curl "api.ipify.org?format=json" {"ip":"167.220.196.42"} </code></pre>
3
2016-02-10T14:00:15Z
[ "python", "ip-address", "tcp" ]
Adding twisted code to a pygtk app
613,777
<p>I have a simple pygtk app using urllib2, what changes should I make to add working twisted code?</p> <p>The pbgtk2.py example it's confusing</p>
0
2009-03-05T06:28:20Z
614,449
<p>You switch from using the gtk mainloop to the right <a href="http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto11" rel="nofollow">Twisted reactor</a>. Or you decide to run Twisted in a separate thread using <a href="http://unpythonic.blogspot.com/2008/10/what-twisted-could-learn-from-kamaelia.html" rel="nofollow">reactor.run(installSignalHandlers=0), and stay with the gtk mainloop</a>.</p> <p>You decide if you want to defer the urllib2 call to <a href="http://twistedmatrix.com/documents/current/api/twisted.internet.threads.deferToThread.html" rel="nofollow">its own thread</a>, or if you want to rewrite that code using <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.web.client.html" rel="nofollow">Twisted's HTTP client libraries</a>.</p> <p>You go to the Twisted mailing list or IRC channel and <a href="http://twistedmatrix.com/trac/wiki/TwistedCommunity" rel="nofollow">ask for help</a>.</p>
4
2009-03-05T11:48:22Z
[ "python", "pygtk", "twisted" ]
Why is the regular expression returning an error in python?
614,205
<p>Am trying the following regular expression in python but it returns an error</p> <pre><code>import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?&lt;=[WORD])\w+',str(line)) m.group(0) </code></pre> <p>i get the following error:</p> <p><strong>AttributeError: 'NoneType' object has no attribute 'group'</strong></p>
2
2009-03-05T10:13:47Z
614,217
<p>This is happening because the regular expression wasn't matched. Therefore m is None and of course you can't access group[0]. You need to first test that the search was successful, before trying to access group members.</p>
4
2009-03-05T10:16:21Z
[ "python", "regex" ]
Why is the regular expression returning an error in python?
614,205
<p>Am trying the following regular expression in python but it returns an error</p> <pre><code>import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?&lt;=[WORD])\w+',str(line)) m.group(0) </code></pre> <p>i get the following error:</p> <p><strong>AttributeError: 'NoneType' object has no attribute 'group'</strong></p>
2
2009-03-05T10:13:47Z
614,220
<p><a href="http://docs.python.org/library/re.html#re.search" rel="nofollow">re.search documentation says</a>:</p> <blockquote> <p>Return <strong>None</strong> if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.</p> </blockquote>
2
2009-03-05T10:17:19Z
[ "python", "regex" ]
Why is the regular expression returning an error in python?
614,205
<p>Am trying the following regular expression in python but it returns an error</p> <pre><code>import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?&lt;=[WORD])\w+',str(line)) m.group(0) </code></pre> <p>i get the following error:</p> <p><strong>AttributeError: 'NoneType' object has no attribute 'group'</strong></p>
2
2009-03-05T10:13:47Z
614,221
<pre><code>&gt;&gt;&gt; help(re.search) Help on function search in module re: search(pattern, string, flags=0) Scan through string looking for a match to the pattern, returning a match object, or None if no match was found. </code></pre> <p>Look at the last line: <strong>returning None if no match was found</strong></p>
2
2009-03-05T10:17:31Z
[ "python", "regex" ]
Why is the regular expression returning an error in python?
614,205
<p>Am trying the following regular expression in python but it returns an error</p> <pre><code>import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?&lt;=[WORD])\w+',str(line)) m.group(0) </code></pre> <p>i get the following error:</p> <p><strong>AttributeError: 'NoneType' object has no attribute 'group'</strong></p>
2
2009-03-05T10:13:47Z
614,295
<p>BTW, your regular expression is incorrect. If you look for 'WORD', it should be just 'WORD'. <code>str</code> is also extraneous. Your code should look like this:</p> <pre><code>m = re.search('WORD', line) if m: print m.group[0] </code></pre> <p>Your original regexp will return probably unexpected and undesired results:</p> <pre><code>&gt;&gt;&gt; m = re.search('(?&lt;=[WORD])\w+', 'WORDnet') &gt;&gt;&gt; m.group(0) 'ORDnet' </code></pre>
1
2009-03-05T10:46:45Z
[ "python", "regex" ]
Why is the regular expression returning an error in python?
614,205
<p>Am trying the following regular expression in python but it returns an error</p> <pre><code>import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?&lt;=[WORD])\w+',str(line)) m.group(0) </code></pre> <p>i get the following error:</p> <p><strong>AttributeError: 'NoneType' object has no attribute 'group'</strong></p>
2
2009-03-05T10:13:47Z
614,643
<p>Two issues:</p> <ol> <li><p>your pattern does not match, therefore <code>m</code> is set to <code>None</code>, and <code>None</code> has no <code>group</code> attribute.</p></li> <li><p>I believe you meant either:</p> <pre><code>m= re.search(r"(?&lt;=WORD)\w+", str(line)) </code></pre> <p>as entered, or</p> <pre><code>m= re.search(r"(?P&lt;WORD&gt;\w+)", str(line)) </code></pre> <p>The former matches "abc" in "WORDabc def"; the latter matches "abc" in "abc def" and the match object will have a <code>.group("WORD")</code> containing "abc". (Using r"" strings is generally a good idea when specifying regular expressions.)</p></li> </ol>
2
2009-03-05T12:53:45Z
[ "python", "regex" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,474
<p>I think a regex is overkill if you only want to deal with the above two cases. Here's what I'd do-</p> <pre><code>&gt;&gt;&gt; case1 = "str1=str2" &gt;&gt;&gt; case2 = "str1 = str2" &gt;&gt;&gt; case2.split() ['str1', '=', 'str2'] &gt;&gt;&gt; ''.join(case2.split()) 'str1=str2' &gt;&gt;&gt; case1[5:] 'str2' &gt;&gt;&gt; ''.join(case2.split())[5:] 'str2' &gt;&gt;&gt; </code></pre> <h2><strong>Assumption</strong></h2> <p>I assume you are looking for the specific token 'str1'. I also assume that str1 can be assigned different values. Something like what you'd have in a configuration file => propertyName = value.</p> <p>This is just my opinion.</p> <p>I knew that other ways were possible! SilentGhost gives a nice (better!) alternative.</p> <p>Hope this helps.</p>
0
2009-03-05T11:56:41Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,477
<pre><code>re.search(r'=\s*(.*)', 'str = str2').group(1) </code></pre> <p>or if you just want a single word:</p> <pre><code>re.search(r'=\s*(\w+)', 'str = str2').group(1) </code></pre> <p>Extended to specific initial string:</p> <pre><code>re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1) </code></pre> <p><code>\b</code> = word boundary, so won't match <code>"somestr=foo"</code> </p> <p>It would be quicker to go trough all options once, instead of searching for single options one at the time:</p> <pre><code>option_str = "a=b, c=d, g=h" options = dict(re.findall(r'(\w+)\s*=\s*(\w+)', option_str)) options['c'] # -&gt; 'd' </code></pre>
3
2009-03-05T11:57:28Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,508
<p>if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on <code>=</code> and strip (or even lstrip) last element of a resulting tuple:</p> <pre><code>&gt;&gt;&gt; case = 'str = str2' &gt;&gt;&gt; case.partition('=')[2].lstrip() 'str2' </code></pre> <p>it'll be much faster than regexps. and just to show how fast i've made a simple test:</p> <pre><code>&gt;&gt;&gt; timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 &gt;&gt;&gt; timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 &gt;&gt;&gt; timeit.timeit('import re') 0.65663786250422618 </code></pre>
8
2009-03-05T12:08:53Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,511
<p>Expanding on @batbrat's answer, and the other suggestions, you can use <code>re.split()</code> to separate the input string. The pattern can use <code>\s</code> (whitespace) or an explicit space.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; c1="str1=str2" &gt;&gt;&gt; c2="str1 = str2" &gt;&gt;&gt; re.split(' ?= ?',c1) ['str1', 'str2'] &gt;&gt;&gt; re.split(' ?= ?',c2) ['str1', 'str2'] &gt;&gt;&gt; re.split(r'\s?=\s?',c1) ['str1', 'str2'] &gt;&gt;&gt; re.split(r'\s?=\s?',c2) ['str1', 'str2'] &gt;&gt;&gt; </code></pre>
0
2009-03-05T12:09:23Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,528
<p>If your data is fixed then you can do this without using regex. Just split it on '='. For example:</p> <pre><code>&gt;&gt;&gt; case1 = "str1=str2" &gt;&gt;&gt; case2 = "str1 = str2" &gt;&gt;&gt; str2 = case1.split('=')[1].strip() &gt;&gt;&gt; str2 = case2.split('=')[1].strip() </code></pre> <p>This <code>YOURCASE.split('=')[1].strip()</code> statement will work for any cases.</p>
1
2009-03-05T12:14:37Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
614,684
<p>Two cases:</p> <ul> <li><p>(case 1) if there is a single space before the '=', then there <strong>must</strong> also be a single space after the '='</p> <pre><code>m=re.search(r'(?&lt;=\S)(?:\s=\s|=)(\w+)','str = str2') print m.group(1) </code></pre></li> <li><p>(case 2) otherwise,</p> <pre><code>m=re.search(r'(?&lt;=\S)\s?=\s?(\w+)','str = str2') print m.group(1) </code></pre></li> </ul> <p>In the first case, you could also use the "(?P=…" construct for the second space or lack of it, but it still wouldn't work for a <em>positive lookbehind assertion</em>, since it wouldn't be a constant length subexpression.</p>
0
2009-03-05T13:09:22Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
618,355
<p>Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: <a href="http://kodos.sf.net" rel="nofollow">http://kodos.sf.net</a>.</p>
0
2009-03-06T10:24:49Z
[ "python", "regex", "string" ]
How do i write a regular expression for the following pattern in python?
614,458
<p>How do i look for the following pattern using regular expression in python? for the two cases</p> <p>Am looking for str2 after the "=" sign </p> <ul> <li>Case 1: <code>str1=str2</code></li> <li>Case 2: <code>str1 = str2</code></li> </ul> <p>please note there can be a <strong>space or none</strong> between the either side of the "=" sign</p> <p>Mine is like this, but only works for one of the cases!</p> <pre><code>m=re.search('(?&lt;=str\s\=\s)\w+','str = str2') </code></pre> <p>returns str2</p> <p>Help!</p> <p>Gath</p>
0
2009-03-05T11:50:50Z
629,318
<p>Simply use split function</p>
1
2009-03-10T08:25:01Z
[ "python", "regex", "string" ]