Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python 3.x - Dict Values disappear while sorting

i wrote a little function to sort a little dict like

unsorted_dict = {
    "A": [2,4,6,1,2,8,0],
    "Z": 20,
    "B": {
        4: "hallo",
        0: [4,4,4,5,1],
        1: {
            "b": "Potato",
            "a": [ "b", "d", "c"]
        }
    }
}

And in theorie it works. After the funktion below, my LIST looks like this

[{'A': None, 'B': None, 'Z': None}, [0, 1, 2, 2, 4, 6, 8], {0: None, 1: None, 4: None}, [1, 4, 4, 4, 5], {'a': None, 'b': None}, ['b', 'c', 'd'], 'Potato', 'hallo', 20]
LIST = list()

def sort(unsorted):
    """ function to create a list from a dict. """                          
    if type(unsorted) is dict:                   
        unsorted = dict(sorted(unsorted.items()))
        LIST.append(unsorted)                                      
        for key, value in unsorted.items():      
            unsorted[key]= sort(value)           
    elif type(unsorted) is int:                  
        LIST.append(unsorted)                    
    elif type(unsorted) is str:                  
        LIST.append(unsorted)                    
    else:
        """ bookmark """                                
        unsorted = sorted(unsorted)              
        LIST.append(unsorted)                    

my question is, why the values of the dict disappear during the regressive list-appending. its a qiet nice side-effect because i can easy fill the "empty" dicts with the elements placed on the right of them, but why does it work?

After the first iteration, my LIST has the whole dict inside, just sorted by key. But on the second iteration, when it sorts the first value of the first dict (at bookmark) - in this case the list of A-, and the list gets appended to LIST, it automaticly disappears in the dict in LIST

[{'A': None, 'B': {4: 'hallo', 0: [4, 4, 4, 5, 1], 1: {'b': 'Potato', 'a': ['b', 'd', 'c']}}, 'Z': 20}, [0, 1, 2, 2, 4, 6, 8]]

Sry for the strange description but i am really confused.

question from:https://stackoverflow.com/questions/65626842/dict-values-disappear-while-sorting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...