Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7601

Re: Dictionaries and incrementing keys

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!feeder.erje.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail
From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: Dictionaries and incrementing keys
Followup-To comp.lang.python
Date Tue, 14 Jun 2011 13:16:47 +0200
Organization None
Lines 20
Message-ID <it7fu4$rc5$1@solani.org> (permalink)
References <slrnivefl8.47d.steve@news.mixmin.net>
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Trace solani.org 1308050181 28037 eJwFwYkRADAEBMCWvGeUQ9B/Cdl1BeOFwWF+fksTedOkS9GoM44W3hV94iaEyqnJoYgx7w8nNRFV (14 Jun 2011 11:16:21 GMT)
X-Complaints-To abuse@news.solani.org
NNTP-Posting-Date Tue, 14 Jun 2011 11:16:21 +0000 (UTC)
X-User-ID eJwFwQkBACAIA8BK8mxoHFDoH8E7GIU3nKBjMMXnGxSDYELhq1RMOmxn2tXgQrECp3fUmc7nsdpVj00+fiQiFKg=
Cancel-Lock sha1:XYKcPJ2lx4dpoD0cdbaxmcZipYY=
X-NNTP-Posting-Host eJwNxsEBwzAIA8CVTIQAjUMd2H+E9F5HhMVND4ZzuXpSCxti+tzzf8evXuGRwK0pTjZ1Q2btY8eRdRb0VmFsLZAje4kQ5wOoHhih
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:7601

Followups directed to: comp.lang.python

Show key headers only | View raw


Steve Crook wrote:

> I've always done key creation/incrementation using:
> 
> if key in dict:
>     dict[key] += 1
> else:
>     dict[key] = 1

Your way is usually faster than
 
> dict[key] = dict.get(key, 0) + 1
> 
> Whilst certainly more compact, I'd be interested in views on how
> pythonesque this method is.

You may also consider

http://docs.python.org/library/collections.html#collections.defaultdict
http://docs.python.org/library/collections.html#collections.Counter

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Dictionaries and incrementing keys Steve Crook <steve@mixmin.net> - 2011-06-14 10:57 +0000
  Re: Dictionaries and incrementing keys Peter Otten <__peter__@web.de> - 2011-06-14 13:16 +0200
    Re: Dictionaries and incrementing keys AlienBaby <matt.j.warren@gmail.com> - 2011-06-14 05:37 -0700
      Re: Dictionaries and incrementing keys Steve Crook <steve@mixmin.net> - 2011-06-14 12:53 +0000
        Re: Dictionaries and incrementing keys Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-14 13:26 +0000
    Re: Dictionaries and incrementing keys Steve Crook <steve@mixmin.net> - 2011-06-14 12:57 +0000
  Re: Dictionaries and incrementing keys Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-14 13:24 +0000
  Re: Dictionaries and incrementing keys Asen Bozhilov <asen.bozhilov@gmail.com> - 2011-06-14 09:30 -0700
  Re: Dictionaries and incrementing keys Raymond Hettinger <python@rcn.com> - 2011-06-25 01:13 -0700

csiph-web