python generator does not work as my expectation












0















class ObjA(object):
def __init__(self, self_id):
self.id = self_id
self.sub_items =

def __str__(self):
return "objA{id=%d;sub_items=%s}" % (self.id, str(self.sub_items))

__repr__ = __str__


lst =
a1 = ObjA(1)
a1.sub_items.append(1)
a1.sub_items.append(2)
a2 = ObjA(2)
a2.sub_items.append(3)
lst.append(a1)
lst.append(a2)
result = {a.id: {tmp: a} for a in lst for tmp in a.sub_items}
print result


the result is:



{1: {2: objA{id=1;sub_items=[1, 2]}}, 
2: {3: objA{id=2;sub_items=[3]}}};


but i want it like:



{1: {1: objA{id=1;sub_items=[1, 2]},
2: objA{id=1;sub_items=[1, 2]}},
2: {3: objA{id=2;sub_items=[3]}}};


something is wrong.










share|improve this question




















  • 1





    There are no generators in your example.

    – DYZ
    Nov 26 '18 at 5:38











  • it is actually a Dict Comprehension.

    – 王小敏
    Nov 26 '18 at 7:12
















0















class ObjA(object):
def __init__(self, self_id):
self.id = self_id
self.sub_items =

def __str__(self):
return "objA{id=%d;sub_items=%s}" % (self.id, str(self.sub_items))

__repr__ = __str__


lst =
a1 = ObjA(1)
a1.sub_items.append(1)
a1.sub_items.append(2)
a2 = ObjA(2)
a2.sub_items.append(3)
lst.append(a1)
lst.append(a2)
result = {a.id: {tmp: a} for a in lst for tmp in a.sub_items}
print result


the result is:



{1: {2: objA{id=1;sub_items=[1, 2]}}, 
2: {3: objA{id=2;sub_items=[3]}}};


but i want it like:



{1: {1: objA{id=1;sub_items=[1, 2]},
2: objA{id=1;sub_items=[1, 2]}},
2: {3: objA{id=2;sub_items=[3]}}};


something is wrong.










share|improve this question




















  • 1





    There are no generators in your example.

    – DYZ
    Nov 26 '18 at 5:38











  • it is actually a Dict Comprehension.

    – 王小敏
    Nov 26 '18 at 7:12














0












0








0








class ObjA(object):
def __init__(self, self_id):
self.id = self_id
self.sub_items =

def __str__(self):
return "objA{id=%d;sub_items=%s}" % (self.id, str(self.sub_items))

__repr__ = __str__


lst =
a1 = ObjA(1)
a1.sub_items.append(1)
a1.sub_items.append(2)
a2 = ObjA(2)
a2.sub_items.append(3)
lst.append(a1)
lst.append(a2)
result = {a.id: {tmp: a} for a in lst for tmp in a.sub_items}
print result


the result is:



{1: {2: objA{id=1;sub_items=[1, 2]}}, 
2: {3: objA{id=2;sub_items=[3]}}};


but i want it like:



{1: {1: objA{id=1;sub_items=[1, 2]},
2: objA{id=1;sub_items=[1, 2]}},
2: {3: objA{id=2;sub_items=[3]}}};


something is wrong.










share|improve this question
















class ObjA(object):
def __init__(self, self_id):
self.id = self_id
self.sub_items =

def __str__(self):
return "objA{id=%d;sub_items=%s}" % (self.id, str(self.sub_items))

__repr__ = __str__


lst =
a1 = ObjA(1)
a1.sub_items.append(1)
a1.sub_items.append(2)
a2 = ObjA(2)
a2.sub_items.append(3)
lst.append(a1)
lst.append(a2)
result = {a.id: {tmp: a} for a in lst for tmp in a.sub_items}
print result


the result is:



{1: {2: objA{id=1;sub_items=[1, 2]}}, 
2: {3: objA{id=2;sub_items=[3]}}};


but i want it like:



{1: {1: objA{id=1;sub_items=[1, 2]},
2: objA{id=1;sub_items=[1, 2]}},
2: {3: objA{id=2;sub_items=[3]}}};


something is wrong.







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 5:35









DYZ

27.9k62150




27.9k62150










asked Nov 26 '18 at 5:30









王小敏王小敏

31




31








  • 1





    There are no generators in your example.

    – DYZ
    Nov 26 '18 at 5:38











  • it is actually a Dict Comprehension.

    – 王小敏
    Nov 26 '18 at 7:12














  • 1





    There are no generators in your example.

    – DYZ
    Nov 26 '18 at 5:38











  • it is actually a Dict Comprehension.

    – 王小敏
    Nov 26 '18 at 7:12








1




1





There are no generators in your example.

– DYZ
Nov 26 '18 at 5:38





There are no generators in your example.

– DYZ
Nov 26 '18 at 5:38













it is actually a Dict Comprehension.

– 王小敏
Nov 26 '18 at 7:12





it is actually a Dict Comprehension.

– 王小敏
Nov 26 '18 at 7:12












1 Answer
1






active

oldest

votes


















4














The nested comprehension you are looking for is the following:



{a.id: {tmp: a for tmp in a.sub_items} for a in lst}
# {1: {1: objA{id=1;sub_items=[1, 2]},
# 2: objA{id=1;sub_items=[1, 2]}},
# 2: {3: objA{id=2;sub_items=[3]}}}


Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.






share|improve this answer

























    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',
    autoActivateHeartbeat: false,
    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%2f53475206%2fpython-generator-does-not-work-as-my-expectation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    The nested comprehension you are looking for is the following:



    {a.id: {tmp: a for tmp in a.sub_items} for a in lst}
    # {1: {1: objA{id=1;sub_items=[1, 2]},
    # 2: objA{id=1;sub_items=[1, 2]}},
    # 2: {3: objA{id=2;sub_items=[3]}}}


    Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.






    share|improve this answer






























      4














      The nested comprehension you are looking for is the following:



      {a.id: {tmp: a for tmp in a.sub_items} for a in lst}
      # {1: {1: objA{id=1;sub_items=[1, 2]},
      # 2: objA{id=1;sub_items=[1, 2]}},
      # 2: {3: objA{id=2;sub_items=[3]}}}


      Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.






      share|improve this answer




























        4












        4








        4







        The nested comprehension you are looking for is the following:



        {a.id: {tmp: a for tmp in a.sub_items} for a in lst}
        # {1: {1: objA{id=1;sub_items=[1, 2]},
        # 2: objA{id=1;sub_items=[1, 2]}},
        # 2: {3: objA{id=2;sub_items=[3]}}}


        Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.






        share|improve this answer















        The nested comprehension you are looking for is the following:



        {a.id: {tmp: a for tmp in a.sub_items} for a in lst}
        # {1: {1: objA{id=1;sub_items=[1, 2]},
        # 2: objA{id=1;sub_items=[1, 2]}},
        # 2: {3: objA{id=2;sub_items=[3]}}}


        Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 26 '18 at 5:42

























        answered Nov 26 '18 at 5:36









        schwobasegglschwobaseggl

        37.4k32442




        37.4k32442
































            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53475206%2fpython-generator-does-not-work-as-my-expectation%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







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga