Python: sort dictionary with tuples as key by the value

This question already has an answer here:

  • How do I sort a dictionary by value? 38 answers

  • This gives what you want, sorted. But it's not in a dictionary at the end, since you can't sort a dictionary.

    d={('w1','u1'):3,('w1','u2'):8,('w2','u1'):1,('w1','u3'):11,('w2','u3'):6}
    
    d2 = {}
    
    for (w,u) , value in d.items():
        if w not in d2:
            d2[w] = [(u,value)]
        else:
            d2[w].append((u, value))
    
    
    for key, values in d2.items():
        print key, ":t", sorted(values, key=lambda x: -x[1]), "n"
    

    which gives:

    w2 :    [('u3', 6), ('u1', 1)] 
    
    w1 :    [('u3', 11), ('u2', 8), ('u1', 3)] 
    

    Given the final dict you are after, it doesn't seem to me you need to sort. Just iterate through the key-value pairs, and rearrange them into a new dict:

    d = {('w1', 'u1'): 3, ('w1', 'u2'): 8, ('w2', 'u1'): 1, ('w1', 'u3'): 11,
         ('w2', 'u3'): 6}
    result = {}
    for (w, u), val in d.iteritems():
        result.setdefault(w, {})[u] = val
    print(result)
    

    yields

    {'w2': {'u1': 1, 'u3': 6}, 'w1': {'u1': 3, 'u3': 11, 'u2': 8}}
    
    链接地址: http://www.djcxy.com/p/18160.html

    上一篇: 如何使用字典功能?

    下一篇: Python:通过值将字典与元组进行排序