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
4.6k views
in Technique[技术] by (71.8m points)

associative array - Sorting multi-dictionary in python

I have a datastructure like this:

poll = {
  'LINK' : {'MoonRaccoon' : 1, 'TheDirtyTree' : 1},
  'ZRX' : {'MoonRaccoon' : 1, 'Dontcallmeskaface' : 1, 'TheDirtyTree' : 1},  
  'XRP' : {'Dontcallmeskaface' : 1},
  'XLM' : {'aeon' : 1, 'Bob' : 1} 
}

I want it to ultimately print like this ordered by the number of who have requested each, then ticker symbol alphabetically, then the users also alphabetically

!pollresults

ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree
LINK : MoonRaccoon, TheDirtyTree
XLM : aeon, Bob
XRP: Dontcallmeskaface

Anyone really good at sorting that could help me do this.. I'm really new to python and super rusty at coding in general.

Thanks for any help.


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

1 Reply

0 votes
by (71.8m points)

Here you get a oneliner:

print (sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True))

Output:

[('ZRX', {'MoonRaccoon': 1, 'Dontcallmeskaface': 1, 'TheDirtyTree': 1}), ('LINK', {'MoonRaccoon': 1, 'TheDirtyTree': 1}), ('XLM', {'aeon': 1, 'Bob': 1}), ('XRP', {'Dontcallmeskaface': 1})]

To pretty print:

lst = sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)

for elem in lst:
    print (elem[0],":"," ".join(elem[1].keys()))

And because I really like oneliners, everything in one line!

print ("
".join([" : ".join([elem[0]," ".join(list(elem[1].keys()))]) for elem in sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)]))

Output:

ZRX : MoonRaccoon Dontcallmeskaface TheDirtyTree
LINK : MoonRaccoon TheDirtyTree
XLM : aeon Bob
XRP : Dontcallmeskaface

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

...