如何按所需方式打印输出?

2024-03-28 16:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印的嵌套字典输出所需的方式,但没有得到任何想法做同样的。有谁能帮忙处理这个案子吗。你知道吗

#!/usr/bin/python

#Using python 2.7

li= [ {1: {"count_1": 12, "count_3": 899, "count_2": 100}},
      {2: {"count_1": 13, "count_3": 100, "count_2": 200}},
      {3: {"count_1": 14, "count_3": 999, "count_2": 300}},
      {4: {"count_1": 15, "count_3": 99, "count_2": 400}}]

fmt = "{:} {:}  {:}  {:}   {:}  "
print fmt.format("name", "stat1", "stat2", "stat3", "stat4")

for dict_data in li:
  for parent_key,value in dict_data.iteritems():
     for k,v in value.iteritems():
         print k, "->", v

获取输出为:

name, stat1  stat2  stat3   stat4  
count_3 -> 899
count_2 -> 100
count_1 -> 12
count_3 -> 100
count_2 -> 200
count_1 -> 13
count_3 -> 999
count_2 -> 300
count_1 -> 14
count_3 -> 99
count_2 -> 400
count_1 -> 15

预期产量:

    name       stat1  stat2  stat3   stat4  
    count_3     899     100   999      99
    count_2     100     200   300      400
    count_1     12      13    14       15

使用:python2.7,我想避免pandas


Tags: nameinfordatavaluecountlidict
1条回答
网友
1楼 · 发布于 2024-03-28 16:41:04

这里有一种方法。您可以提取“行名称”并在每行都位于单独的行时对其进行排序,然后从li中提取每行的值:

fmt = "{:}\t{:}\t{:}\t{:}\t{:}  "
print(fmt.format("name", "stat1", "stat2", "stat3", "stat4"))

rows = sorted(li[0][1].keys(), reverse=True) # ['count_3', 'count_2', 'count_1']
for rname in rows:
    stats = [val[rname] for d in li for val in d.values()]
    print(fmt.format(rname, *stats))

输出

name    stat1   stat2   stat3   stat4                                                                                                                                              
count_3 899     100     999     99                                                                                                                                                 
count_2 100     200     300     400                                                                                                                                                
count_1 12      13      14      15

相关问题 更多 >