Need a defaultdict with values as two lists









up vote
0
down vote

favorite












In Python, I want something like



dict = defaultdict((list,list))


Essentially, with every key I want two lists!



With the above snippet I get the error first argument must be callable. How can I achieve this ?










share|improve this question





















  • @Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
    – midi
    Nov 11 at 18:22














up vote
0
down vote

favorite












In Python, I want something like



dict = defaultdict((list,list))


Essentially, with every key I want two lists!



With the above snippet I get the error first argument must be callable. How can I achieve this ?










share|improve this question





















  • @Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
    – midi
    Nov 11 at 18:22












up vote
0
down vote

favorite









up vote
0
down vote

favorite











In Python, I want something like



dict = defaultdict((list,list))


Essentially, with every key I want two lists!



With the above snippet I get the error first argument must be callable. How can I achieve this ?










share|improve this question













In Python, I want something like



dict = defaultdict((list,list))


Essentially, with every key I want two lists!



With the above snippet I get the error first argument must be callable. How can I achieve this ?







python dictionary defaultdict






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 18:12









midi

7110




7110











  • @Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
    – midi
    Nov 11 at 18:22
















  • @Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
    – midi
    Nov 11 at 18:22















@Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
– midi
Nov 11 at 18:22




@Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
– midi
Nov 11 at 18:22












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










Give as parameter to defaultdict a function that creates your empty lists:



from collections import defaultdict

def pair_of_lists():
return [, ]

d = defaultdict(pair_of_lists)

d[1][0].append(3)
d[1][1].append(42)

print(d)
# defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, 1: [[3], [42]])





share|improve this answer



























    up vote
    0
    down vote













    It is not some kind of type inference, you just provide a function that generates default value. While int, list, dict without argument generate 0, , , which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as



    di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))


    While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.



    from collections import defaultdict
    l1 =
    l2 = ["another", "default", "list"]
    di = defaultdict(lambda : [ l1, l2] )
    print (di[3])





    share|improve this answer






















    • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
      – midi
      Nov 11 at 18:23











    • This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
      – midi
      Nov 11 at 18:27











    • @midi where you write list, it doesn’t get called so you should write either or list()
      – N Chauhan
      Nov 11 at 18:43










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251716%2fneed-a-defaultdict-with-values-as-two-lists%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Give as parameter to defaultdict a function that creates your empty lists:



    from collections import defaultdict

    def pair_of_lists():
    return [, ]

    d = defaultdict(pair_of_lists)

    d[1][0].append(3)
    d[1][1].append(42)

    print(d)
    # defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, 1: [[3], [42]])





    share|improve this answer
























      up vote
      1
      down vote



      accepted










      Give as parameter to defaultdict a function that creates your empty lists:



      from collections import defaultdict

      def pair_of_lists():
      return [, ]

      d = defaultdict(pair_of_lists)

      d[1][0].append(3)
      d[1][1].append(42)

      print(d)
      # defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, 1: [[3], [42]])





      share|improve this answer






















        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Give as parameter to defaultdict a function that creates your empty lists:



        from collections import defaultdict

        def pair_of_lists():
        return [, ]

        d = defaultdict(pair_of_lists)

        d[1][0].append(3)
        d[1][1].append(42)

        print(d)
        # defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, 1: [[3], [42]])





        share|improve this answer












        Give as parameter to defaultdict a function that creates your empty lists:



        from collections import defaultdict

        def pair_of_lists():
        return [, ]

        d = defaultdict(pair_of_lists)

        d[1][0].append(3)
        d[1][1].append(42)

        print(d)
        # defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, 1: [[3], [42]])






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 18:18









        Thierry Lathuille

        7,12182630




        7,12182630






















            up vote
            0
            down vote













            It is not some kind of type inference, you just provide a function that generates default value. While int, list, dict without argument generate 0, , , which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as



            di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))


            While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.



            from collections import defaultdict
            l1 =
            l2 = ["another", "default", "list"]
            di = defaultdict(lambda : [ l1, l2] )
            print (di[3])





            share|improve this answer






















            • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
              – midi
              Nov 11 at 18:23











            • This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
              – midi
              Nov 11 at 18:27











            • @midi where you write list, it doesn’t get called so you should write either or list()
              – N Chauhan
              Nov 11 at 18:43














            up vote
            0
            down vote













            It is not some kind of type inference, you just provide a function that generates default value. While int, list, dict without argument generate 0, , , which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as



            di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))


            While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.



            from collections import defaultdict
            l1 =
            l2 = ["another", "default", "list"]
            di = defaultdict(lambda : [ l1, l2] )
            print (di[3])





            share|improve this answer






















            • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
              – midi
              Nov 11 at 18:23











            • This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
              – midi
              Nov 11 at 18:27











            • @midi where you write list, it doesn’t get called so you should write either or list()
              – N Chauhan
              Nov 11 at 18:43












            up vote
            0
            down vote










            up vote
            0
            down vote









            It is not some kind of type inference, you just provide a function that generates default value. While int, list, dict without argument generate 0, , , which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as



            di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))


            While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.



            from collections import defaultdict
            l1 =
            l2 = ["another", "default", "list"]
            di = defaultdict(lambda : [ l1, l2] )
            print (di[3])





            share|improve this answer














            It is not some kind of type inference, you just provide a function that generates default value. While int, list, dict without argument generate 0, , , which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as



            di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))


            While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.



            from collections import defaultdict
            l1 =
            l2 = ["another", "default", "list"]
            di = defaultdict(lambda : [ l1, l2] )
            print (di[3])






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 12 at 21:20

























            answered Nov 11 at 18:15









            Serge

            1,366522




            1,366522











            • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
              – midi
              Nov 11 at 18:23











            • This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
              – midi
              Nov 11 at 18:27











            • @midi where you write list, it doesn’t get called so you should write either or list()
              – N Chauhan
              Nov 11 at 18:43
















            • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
              – midi
              Nov 11 at 18:23











            • This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
              – midi
              Nov 11 at 18:27











            • @midi where you write list, it doesn’t get called so you should write either or list()
              – N Chauhan
              Nov 11 at 18:43















            Strangely, dict['This'][0].append(1) does not work! what am I missing ?
            – midi
            Nov 11 at 18:23





            Strangely, dict['This'][0].append(1) does not work! what am I missing ?
            – midi
            Nov 11 at 18:23













            This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
            – midi
            Nov 11 at 18:27





            This works : dict = defaultdict(lambda : [, ]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
            – midi
            Nov 11 at 18:27













            @midi where you write list, it doesn’t get called so you should write either or list()
            – N Chauhan
            Nov 11 at 18:43




            @midi where you write list, it doesn’t get called so you should write either or list()
            – N Chauhan
            Nov 11 at 18:43

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251716%2fneed-a-defaultdict-with-values-as-two-lists%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto