Python字典格式化

时间:2018-02-27 19:40:40

标签: python-3.x dictionary tabular

Python3我有一个字母数字字典,如下所示

<form action="#">
  <input type="button" id="showAll" value="Show All"><br />
  <input type="button" id="hideAll" value="Hide All"><br />
</form>

<div class="box" id="greenBox" style="display:none"></div>
<div class="box" id="redBox" style="display:none"></div>
<div class="box" id="blueBox" style="display:none"></div>

我想要一个函数将其打印为  

 e 38088 i 20283 w 8390 b 5293 q 191
 t 30897 s 18831 m 7686 p 5275 z 161
 o 24944 r 16751 c 7301 k 3207
 a 24873 d 15567 y 7139 v 2551
 n 21510 l 12780 g 7109 j 751
 h 20360 u 9624  f 6499 x 439

我尝试将键和值放入列表中,但是因为字典没有排序而随机更改。在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用dict.items()将键值对作为元组列表。然后按值对该列表进行排序。

例如:

d = {
    'a': 24873,
    'b': 5293,
    'c': 7301,
    'd': 15567
}

for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True):
    print("{} {}".format(k, v))

#a 24873
#d 15567
#c 7301
#b 5293

我们使用自定义键lambda x: x[1]对键值对元组进行排序,该键获取元组中索引1处的元素。在这种情况下,该元素是计数。

另外,我们指定reverse=True表示我们希望排序列表按降序排列。

答案 1 :(得分:1)

DataKeyNames

您必须稍微准备一下数据:

from itertools import zip_longest

def printCol(l, numCols=5):
    """Takes a sorted list 'l' and displays it in 'numCols', the first items 
    get into col1, the next in col2 etc."""

    # partition the sorted list
    steps = len(l)//numCols+1
    part = [l[i:i+steps] for i in range(0,len(l),steps)]
    # transpose it into tuple-rows
    zpart = zip_longest(*part,())
    for row in zpart: 
        for t in row: 
            if t:  # zip_longest produces () - do not display them
                print(t[1],t[0], end = " ")
        print("") # newline

输出:

d ={"a":24873,"b":5293  ,"c":7301  ,"d":15567 ,"e":38088 ,
    "f":6499  ,"g":7109  ,"h":20360 ,"i":20283 ,"j":751   ,
    "k":3207  ,"l":12780 ,"m":7686  ,"n":21510 ,"o":24944 ,
    "p":5275  ,"q":191   ,"r":16751 ,"s":18831 ,"t":30897 ,"u":9624  ,
    "v":2551  ,"w":8390  ,"x":439   ,"y":7139  ,"z":161     }

# list comp: create tuples of (count, character) so sort will sort it by count
l = [ (am,ch) for ch,am in d.items()] # create tuples, amount first for sorting
l.sort(reverse=True) # sort descending by count, if equal, then by char

printCol(l,5) # print it

答案 2 :(得分:0)

这是我用传统循环计算出来的解决方案,而不是很多内置函数。 THANKYOU

<pre>
def printTable(value):               
    no_of_rows = len(value)//5+1
    i = 0
    while(i < no_of_rows):
        for j in range(0, len(value), no_of_rows):
            if i+j < len(value):
                print(str(value[i+j][0]).rjust(3),
                      str(value[i+j][1]).rjust(5), end="   ")
        print("")
        i += 1

d ={"a":24873, "b":5293, "c":7301, "d":15567, "e":38088,
    "f":6499, "g":7109, "h":20360, "i":20283, "j":751,
    "k":3207, "l":12780, "m":7686, "n":21510, "o":24944,
    "p":5275, "q":191, "r":16751, "s":18831, "t":30897,
    "u":9624, "v":2551, "w":8390, "x":439, "y":7139,
    "z":161}

dic_to_sortlist = sorted(alph_freq.items(), key=operator.itemgetter(1),
                        reverse=True)

printTable(dic_to_sortlist)
</pre>