1
vote
\$\begingroup\$

I have a data structure that looks like this:

a = {
     'red': ['yellow', 'green', 'purple'],
     'orange': ['fuschia']
    }

This is the code I write to add new elements:

if a.has_key(color):
    a[color].append(path)
else:
    a[color] = [path]

Is there a shorter way to write this?

\$\endgroup\$

locked by Jamal Jul 27 '15 at 22:01

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

Read more about locked posts here.

7
votes
\$\begingroup\$

You can use collections.defaultdict:

from collections import defaultdict

mydict = defaultdict(list)

Now you just need:

mydict[color].append(path)

defaultdict is a subclass of dict that can be initialized to a list, integer...


btw, the use of has_key is discouraged, and in fact has_key has been removed from python 3.2.
When needed, use this by far more pythonic idiom instead:

if color in a:
    ........
\$\endgroup\$
  • \$\begingroup\$ even better is try: a[color].append(path) except KeyError: a[color] = [path] ... and this comment formatting is broken :) \$\endgroup\$ – blaze Dec 21 '11 at 8:58
  • 1
    \$\begingroup\$ @blaze try/except is better? I'd say not. \$\endgroup\$ – Paul Hankin Dec 24 '11 at 21:24
  • \$\begingroup\$ if try is usually successful and exception isn't raised - it's effective. one less "if" to check. \$\endgroup\$ – blaze Dec 26 '11 at 13:11
  • \$\begingroup\$ lots of stuff happening around checking whether operation goes right and whether exception is thrown. besides the semantics of "exception" should be that something, well, exceptional is taking place. I'd avoid using exceptions for regular code flow if a convenient alternative exists \$\endgroup\$ – Nicolas78 Dec 26 '11 at 15:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.