我希望按期望的方式打印嵌套字典的输出,但不希望有任何想法。关于此案,任何人都可以帮忙。
#!/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
使用:Python 2.7,我想避免使用pandas
答案 0 :(得分:2)
这是一种方法。您可以提取“行名”,并在每行分开时首先对其进行排序,然后从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