Cycling nested dictionary valuesHow to make a flat list out of list of listsLoop through all nested dictionary values?How to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryIterating over dictionaries using 'for' loopsHow to access environment variable values?Delete an element from a dictionaryHow to remove a key from a Python dictionary?

What happens to unproductive professors?

What does 오지다 mean?

When I press the space bar it deletes the letters in front of it

What would +1/+2/+3 items be called in game?

What happens when adult Billy Batson says "Shazam"?

BST/GMT to UTC time

Do I have to worry about delays in international trains? (UK, Belgium, Germany)

Why is the ladder of the LM always in the dark side of the LM?

Why don't we give Peah today?

Venice in late October / early November

What adjective means "accurately representitive of reality"?

Misrepresented my work history

What's it called when the bad guy gets eaten?

What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?

Misspelling my name on my mathematical publications

AWS Fargate + Application Load Balancer SSL Termination

Is it okay to roll multiple attacks that all have advantage in one cluster?

Data Encryption by Application vs Data Encryption in Database

Is this a reference to the film Alien in the novel 2010 Odyssey Two?

Why does the US seem to have a rather low economic interest in Africa?

LED glows slightly during soldering

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

Compiler doesn't fail when pushing back a std::unique_ptr into a std::vector

What is this little owl-like bird?



Cycling nested dictionary values


How to make a flat list out of list of listsLoop through all nested dictionary values?How to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryIterating over dictionaries using 'for' loopsHow to access environment variable values?Delete an element from a dictionaryHow to remove a key from a Python dictionary?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I need the ability to breadth-first cycle through the deep-nested properties of a dict. This gets me part of the way there (https://stackoverflow.com/a/10756615/5932433) but the result is not what I need.



Given the following data structure:



data = 
"a":
"c": 1,
"d": 3,
,
"b":
"e": 2,
"f": 4,




I need a method that will return the following:



for _, v in cycle(tree_iter(data)):
print v

# 1 (a -> c)
# 2 (b -> e)
# 3 (a -> d)
# 4 (b -> f)
# 1
# 2
# 3
# 4
# ...etc...


This is the method I have right now for tree_iter:



def tree_iter(nested):
for key, value in nested.iteritems():
if isinstance(value, Mapping):
for inner_key, inner_value in tree_iter(value):
yield inner_key, inner_value
else:
yield key, value


Note that order doesn't need to be guaranteed, as long as it's consistent. Each iteration should cycle through a/b, then cycle through the nested values.










share|improve this question






















  • Also, the structure of the dict will be consistent. All the values will be at level n.

    – thejohnbackes
    Mar 26 at 0:45

















1















I need the ability to breadth-first cycle through the deep-nested properties of a dict. This gets me part of the way there (https://stackoverflow.com/a/10756615/5932433) but the result is not what I need.



Given the following data structure:



data = 
"a":
"c": 1,
"d": 3,
,
"b":
"e": 2,
"f": 4,




I need a method that will return the following:



for _, v in cycle(tree_iter(data)):
print v

# 1 (a -> c)
# 2 (b -> e)
# 3 (a -> d)
# 4 (b -> f)
# 1
# 2
# 3
# 4
# ...etc...


This is the method I have right now for tree_iter:



def tree_iter(nested):
for key, value in nested.iteritems():
if isinstance(value, Mapping):
for inner_key, inner_value in tree_iter(value):
yield inner_key, inner_value
else:
yield key, value


Note that order doesn't need to be guaranteed, as long as it's consistent. Each iteration should cycle through a/b, then cycle through the nested values.










share|improve this question






















  • Also, the structure of the dict will be consistent. All the values will be at level n.

    – thejohnbackes
    Mar 26 at 0:45













1












1








1


1






I need the ability to breadth-first cycle through the deep-nested properties of a dict. This gets me part of the way there (https://stackoverflow.com/a/10756615/5932433) but the result is not what I need.



Given the following data structure:



data = 
"a":
"c": 1,
"d": 3,
,
"b":
"e": 2,
"f": 4,




I need a method that will return the following:



for _, v in cycle(tree_iter(data)):
print v

# 1 (a -> c)
# 2 (b -> e)
# 3 (a -> d)
# 4 (b -> f)
# 1
# 2
# 3
# 4
# ...etc...


This is the method I have right now for tree_iter:



def tree_iter(nested):
for key, value in nested.iteritems():
if isinstance(value, Mapping):
for inner_key, inner_value in tree_iter(value):
yield inner_key, inner_value
else:
yield key, value


Note that order doesn't need to be guaranteed, as long as it's consistent. Each iteration should cycle through a/b, then cycle through the nested values.










share|improve this question














I need the ability to breadth-first cycle through the deep-nested properties of a dict. This gets me part of the way there (https://stackoverflow.com/a/10756615/5932433) but the result is not what I need.



Given the following data structure:



data = 
"a":
"c": 1,
"d": 3,
,
"b":
"e": 2,
"f": 4,




I need a method that will return the following:



for _, v in cycle(tree_iter(data)):
print v

# 1 (a -> c)
# 2 (b -> e)
# 3 (a -> d)
# 4 (b -> f)
# 1
# 2
# 3
# 4
# ...etc...


This is the method I have right now for tree_iter:



def tree_iter(nested):
for key, value in nested.iteritems():
if isinstance(value, Mapping):
for inner_key, inner_value in tree_iter(value):
yield inner_key, inner_value
else:
yield key, value


Note that order doesn't need to be guaranteed, as long as it's consistent. Each iteration should cycle through a/b, then cycle through the nested values.







python algorithm iterator






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 0:21









thejohnbackesthejohnbackes

9286 silver badges16 bronze badges




9286 silver badges16 bronze badges












  • Also, the structure of the dict will be consistent. All the values will be at level n.

    – thejohnbackes
    Mar 26 at 0:45

















  • Also, the structure of the dict will be consistent. All the values will be at level n.

    – thejohnbackes
    Mar 26 at 0:45
















Also, the structure of the dict will be consistent. All the values will be at level n.

– thejohnbackes
Mar 26 at 0:45





Also, the structure of the dict will be consistent. All the values will be at level n.

– thejohnbackes
Mar 26 at 0:45












1 Answer
1






active

oldest

votes


















0














Your current code appears to do a DFS, so you can return a list of lists from the DFS, zip them, and then flatten. Not the most elegant, but it should work.



def tree_iter_dfs(nested):
for key, value in nested.iteritems():
if isinstance(value, Mapping):
yield value.items()
else:
yield [(key, value)]

# https://stackoverflow.com/a/952952/5309823
def flatten(l):
return [item for sublist in l for item in sublist]

def tree_iter_bfs(nested):
dfs = tree_iter_dfs(nested)
return flatten(zip(*dfs))

print(list(tree_iter_bfs(data)))
# [('c', 1), ('e', 2), ('d', 3), ('f', 4)]


Change things around to iterables as necessary; I didn't know what version of Python you were using, etc.






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%2f55348191%2fcycling-nested-dictionary-values%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









    0














    Your current code appears to do a DFS, so you can return a list of lists from the DFS, zip them, and then flatten. Not the most elegant, but it should work.



    def tree_iter_dfs(nested):
    for key, value in nested.iteritems():
    if isinstance(value, Mapping):
    yield value.items()
    else:
    yield [(key, value)]

    # https://stackoverflow.com/a/952952/5309823
    def flatten(l):
    return [item for sublist in l for item in sublist]

    def tree_iter_bfs(nested):
    dfs = tree_iter_dfs(nested)
    return flatten(zip(*dfs))

    print(list(tree_iter_bfs(data)))
    # [('c', 1), ('e', 2), ('d', 3), ('f', 4)]


    Change things around to iterables as necessary; I didn't know what version of Python you were using, etc.






    share|improve this answer



























      0














      Your current code appears to do a DFS, so you can return a list of lists from the DFS, zip them, and then flatten. Not the most elegant, but it should work.



      def tree_iter_dfs(nested):
      for key, value in nested.iteritems():
      if isinstance(value, Mapping):
      yield value.items()
      else:
      yield [(key, value)]

      # https://stackoverflow.com/a/952952/5309823
      def flatten(l):
      return [item for sublist in l for item in sublist]

      def tree_iter_bfs(nested):
      dfs = tree_iter_dfs(nested)
      return flatten(zip(*dfs))

      print(list(tree_iter_bfs(data)))
      # [('c', 1), ('e', 2), ('d', 3), ('f', 4)]


      Change things around to iterables as necessary; I didn't know what version of Python you were using, etc.






      share|improve this answer

























        0












        0








        0







        Your current code appears to do a DFS, so you can return a list of lists from the DFS, zip them, and then flatten. Not the most elegant, but it should work.



        def tree_iter_dfs(nested):
        for key, value in nested.iteritems():
        if isinstance(value, Mapping):
        yield value.items()
        else:
        yield [(key, value)]

        # https://stackoverflow.com/a/952952/5309823
        def flatten(l):
        return [item for sublist in l for item in sublist]

        def tree_iter_bfs(nested):
        dfs = tree_iter_dfs(nested)
        return flatten(zip(*dfs))

        print(list(tree_iter_bfs(data)))
        # [('c', 1), ('e', 2), ('d', 3), ('f', 4)]


        Change things around to iterables as necessary; I didn't know what version of Python you were using, etc.






        share|improve this answer













        Your current code appears to do a DFS, so you can return a list of lists from the DFS, zip them, and then flatten. Not the most elegant, but it should work.



        def tree_iter_dfs(nested):
        for key, value in nested.iteritems():
        if isinstance(value, Mapping):
        yield value.items()
        else:
        yield [(key, value)]

        # https://stackoverflow.com/a/952952/5309823
        def flatten(l):
        return [item for sublist in l for item in sublist]

        def tree_iter_bfs(nested):
        dfs = tree_iter_dfs(nested)
        return flatten(zip(*dfs))

        print(list(tree_iter_bfs(data)))
        # [('c', 1), ('e', 2), ('d', 3), ('f', 4)]


        Change things around to iterables as necessary; I didn't know what version of Python you were using, etc.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 0:46









        colecole

        1651 silver badge10 bronze badges




        1651 silver badge10 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55348191%2fcycling-nested-dictionary-values%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

            How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

            해남서초등학교 학교 연혁 학교 동문 외부 링크 둘러보기 메뉴북위 34° 34′ 21″ 동경 126° 35′ 50″ / 북위 34.5726385° 동경 126.5972670°  / 34.5726385; 126.5972670해남서초등학교eh