【问题标题】:Printing a list of dictionaries as a table将字典列表打印为表格
【发布时间】:2019-09-19 14:40:16
【问题描述】:

如何使用 Python 将以下数据格式化为表格形式? 有没有办法按照预期的格式打印/写入数据?

[{"itemcode":null,"productname":"PKS543452","value_2018":null},
{"itemcode":null,"productname":"JHBG6%&9","value_2018":null},
{"itemcode":null,"productname":"VATER3456","value_2018":null},
{"itemcode":null,"productname":"ACDFER3434","value_2018":null}]

预期输出:

|itemcode | Productname | Value_2018 |
|null |PKS543452|null|
|null |JHBG6%&9|null|
|null |VATER3456|null|
|null |ACDFER3434|null|

【问题讨论】:

  • 如果没有看到您的原始代码,我们将不知道如何对您现有的代码库进行更改。请发minimal reproducible example,并充分说明需要修改的内容。没有看到代码,我们不知道你的问题出在哪里。
  • 嗨帕特里克..想了解如何使用内置方法修改列表字典,@glhr 解决方案将帮助..谢谢

标签: python-3.x string data-manipulation


【解决方案1】:

您可以使用pandas 从字典列表中生成数据框:

import pandas as pd

null = "null"
lst = [{"itemcode":null,"productname":"PKS543452","value_2018":null},
{"itemcode":null,"productname":"JHBG6%&9","value_2018":null},
{"itemcode":null,"productname":"VATER3456","value_2018":null},
{"itemcode":null,"productname":"ACDFER3434","value_2018":null}]

df = pd.DataFrame.from_dict(lst)
print(df)

输出:

  itemcode productname value_2018
0     null   PKS543452       null
1     null    JHBG6%&9       null
2     null   VATER3456       null
3     null  ACDFER3434       null

这使得以后操作表格中的数据变得容易。否则,您可以使用内置字符串方法打印所需的输出:

output=[]
col_names = '|' + ' | '.join(lst[0].keys()) + '|' 
print(col_names)

for dic in lst:
    row = '|' + ' | '.join(dic.values()) + '|'
    print(row)

输出:

|itemcode | productname | value_2018|
|null | PKS543452 | null|
|null | JHBG6%&9 | null|
|null | VATER3456 | null|
|null | ACDFER3434 | null|

【讨论】:

  • 谢谢ghlr ...想了解如何使用内置方法操作/更改列表字典。我需要将格式化数据作为 bash 命令的一部分提供。
【解决方案2】:

您也可以这样尝试(不使用 pandas)。我已经注释了代码本身的每一行,所以不要忘记阅读它们。

注意:实际上,您粘贴的列表/数组要么是 json.dumps() 的结果(在 Python 中,是文本),要么是您复制了 API 响应 (JSON)。

null 来自 JavaScript,粘贴的列表/数组不是有效的 Python 列表,但可以将其视为文本并使用 json.loads() 转换回 Python 列表。在这种情况下,null 将转换为 None

这就是为什么要形成想要的 o/p,我们需要另一个检查,例如 "null" if d[key] is None else d[key]

import json

# `null` is used in JavaScript (JSON is JavaScript), so I considered it as string
json_text = """[{"itemcode":null,"productname":"PKS543452","value_2018":null},
{"itemcode":null,"productname":"JHBG6%&9","value_2018":null},
{"itemcode":null,"productname":"VATER3456","value_2018":null},
{"itemcode":null,"productname":"ACDFER3434","value_2018":null}]"""

# Will contain the rows (text)
texts = []

# Converting to original list object, `null`(JavaScript) will transform to `None`(Python)
l = json.loads(json_text)

# Obtain keys (Note that dictionary is an unorederd data type)
# So it is imp to get keys for ordered iteration in all dictionaries of list
# Column may be in different position but related data will be perfect
# If you wish you can hard code the `keys`, here I am getting using `l[0].keys()`
keys = l[0].keys()

# Form header and add to `texts` list
header = '|' + ' | '.join(keys) + " |"
texts.append(header)

# Form body (rows) and append to `texts` list
rows = ['| ' + "|".join(["null" if d[key] is None else d[key] for key in keys]) + "|" for d in l]
texts.extend(rows)

# Print all rows (including header) separated by newline '\n'
answer = '\n'.join(texts)
print(answer)

输出

|itemcode | productname | value_2018 |
| null|PKS543452|null|
| null|JHBG6%&9|null|
| null|VATER3456|null|
| null|ACDFER3434|null|

【讨论】:

  • 非常感谢@hygull 的详细总结
  • 非常感谢。我正在睡觉,我用手机回答,但我写的东西丢失了,我醒来,启动笔记本电脑并写(页面刷新)。不管怎样,你喜欢它。再次感谢@shirop。
  • 如何保持键的固定顺序?每次运行时,键的顺序都会发生变化。在这种情况下,我如何使用 OrderedDict 来保持键的固定顺序?我正在尝试以下但出错了。 l=OrderedDict(json.loads(json_text)) 错误 - ValueError: too many values to unpack (expected 2)
  • 是的,那是正确的。 OrderedDict 负责其项目的插入顺序。在这里,我们直接从json_text 形成,它再次使用json.loads() 转换为无序字典。一种解决方案是通过迭代预定义的键列表来创建OrderedDict。还有一件事,OrderedDict 接受像 OrderedDict(k=90, l=87) 这样的 dict objector 关键字参数,而不是列表。
猜你喜欢
  • 2017-07-12
  • 2015-05-29
  • 2019-03-31
  • 2015-10-03
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 2014-10-13
相关资源
最近更新 更多