Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6564193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:56:10+00:00 2026-05-25T13:56:10+00:00

The following two expressions seem equivalent to me. Which one is preferable? data =

  • 0

The following two expressions seem equivalent to me. Which one is preferable?

data = [('a', 1), ('b', 1), ('b', 2)]

d1 = {}
d2 = {}

for key, val in data:
    # variant 1)
    d1[key] = d1.get(key, []) + [val]
    # variant 2)
    d2.setdefault(key, []).append(val)

The results are the same but which version is better or rather more pythonic?

Personally I find version 2 harder to understand, as to me setdefault is very tricky to grasp. If I understand correctly, it looks for the value of “key” in the dictionary, if not available, enters “[]” into the dict, returns a reference to either the value or “[]” and appends “val” to that reference. While certainly smooth it is not intuitive in the least (at least to me).

To my mind, version 1 is easier to understand (if available, get the value for “key”, if not, get “[]”, then join with a list made up from [val] and place the result in “key”). But while more intuitive to understand, I fear this version is less performant, with all this list creating. Another disadvantage is that “d1” occurs twice in the expression which is rather error-prone. Probably there is a better implementation using get, but presently it eludes me.

My guess is that version 2, although more difficult to grasp for the inexperienced, is faster and therefore preferable. Opinions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T13:56:11+00:00Added an answer on May 25, 2026 at 1:56 pm

    Your two examples do the same thing, but that doesn’t mean get and setdefault do.

    The difference between the two is basically manually setting d[key] to point to the list every time, versus setdefault automatically setting d[key] to the list only when it’s unset.

    Making the two methods as similar as possible, I ran

    from timeit import timeit
    
    print timeit("c = d.get(0, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)
    print timeit("c = d.get(1, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)
    print timeit("d.setdefault(0, []).extend([1])", "d = {1: []}", number = 1000000)
    print timeit("d.setdefault(1, []).extend([1])", "d = {1: []}", number = 1000000)
    

    and got

    0.794723378711
    0.811882272256
    0.724429205999
    0.722129751973
    

    So setdefault is around 10% faster than get for this purpose.

    The get method allows you to do less than you can with setdefault. You can use it to avoid getting a KeyError when the key doesn’t exist (if that’s something that’s going to happen frequently) even if you don’t want to set the key.

    See Use cases for the 'setdefault' dict method and dict.get() method returns a pointer for some more info about the two methods.

    The thread about setdefault concludes that most of the time, you want to use a defaultdict. The thread about get concludes that it is slow, and often you’re better off (speed wise) doing a double lookup, using a defaultdict, or handling the error (depending on the size of the dictionary and your use case).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Are the following two regular expressions functionally equivalent? I ask because I get different
The following two different code snippets seem equivalent to me: var myArray = Array();
In one example from http://leepoint.net/notes-java/data/expressions/precedence.html The following expression 1 + 2 - 3 *
The following two expressions are equivalent: (third (list 1 2 3 4)) (first (nthcdr
I am trying to merge two .net regular expressions into one. The following expressions
Suppose I have the following two strings containing regular expressions. How do I coalesce
The following two forms of jQuery selectors seem to do the same thing: $(div
i have the following two regular expressions (in order btw). 1. ^~/buying/(.*)\?(.*) => foo=
The following code matches the two expressions and prints success. import java.util.regex.Matcher; import java.util.regex.Pattern;
How can I combine two lambda expressions into one using an OR ? I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.