在 python 中对多词典进行排序

Sorting multi-dictionary in python

我有这样的数据结构:

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

我希望它最终像这样打印,按每个请求的人数排序,然后按字母顺序排列股票代码,然后按字母顺序排列用户

!pollresults

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

任何真正擅长排序的人都可以帮助我做到这一点。我真的是 python 的新手,并且在一般编码方面超级生疏。

感谢您的帮助。

词典不能真正排序,但为了打印目的,可以这样做。


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

def print_polls(poll):
    for ticker in sorted(poll, key=lambda t: sum(poll[t].values()), reverse=True):
        print(f"{ticker}: {', '.join(sorted(poll[ticker]))}")

这将为您提供所需的输出

  1. 统计poll中的选票,得到d
  2. d 递减排序
  3. 按照步骤 2 的顺序获取轮询结果,并处理姓名列表的排序
d = [[k, len(v)] for k, v in poll.items()]
d.sort(key=lambda name_vote: (-name_vote[-1],name_vote[0]))
pollresults = [name + ' : ' + ', '.join(sorted(poll[name].keys(), key=str.lower)) for name,vote in d]

结果:

>>> pollresults
['ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree', 'LINK : MoonRaccoon, TheDirtyTree', 'XLM : aeon, Bob', 'XRP : Dontcallmeskaface']

给你一条线:

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

输出:

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

漂亮的打印:

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()))

而且因为我真的很喜欢oneliners,所有的东西都在一条线上!

print ("\n".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)]))

输出:

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