如何在python中动态添加键和值

时间:2015-03-30 04:44:37

标签: python

如何将键动态插入到现有的python词典中,输入是.json文件,输出是.csv文件。

这是.json文件中的输入

[{"FIRSTNAME":"barc","EMAIL":"jahg@jh.com","ADDRESS":"gyuyj"},
{"FIRSTNAME":"rth","EMAIL":"tht@thuyj.com","ADDRESS":"ytju"},
{"FIRSTNAME":"trhy","EMAIL":"klo@pyu.com","ADDRESS":"trght"},
{"FIRSTNAME":"ghy","EMAIL":"ytj@uki.com","ADDRESS":"ukyk"}]

输出是.csv文件(每行应添加其指定的列)

"FIRSTNAME":"barc","rth","trhy","ghy"
"EMAIL":"jahg@jh.com","tht@thuyj.com","klo@pyu.com","ytj@uki.com"
"ADDRESS":"gyuyj","ytju","trght","ukyk"
"LASTNAME":"rgrg","thjuh","sygrbuir","yugfb"
"SALARY":"5665","5476","4565","5677"

如图所示,添加了输入文件和输出,姓氏和工资之间的差异。 类似地,其他字段应该动态添加到相应的列中(即使它是从其他文件中提供的)。

2 个答案:

答案 0 :(得分:0)

你需要2个python模块json和csv。按照步骤

  • 使用json模块读取json文件。
  • 并使用csv模块写入csv文件。在编写时,您需要执行此操作,在csv中添加要添加的任何新信息/列。

答案 1 :(得分:0)

尝试这样:

my_list = [{"FIRSTNAME":"barc","EMAIL":"jahg@jh.com","ADDRESS":"gyuyj"},
{"FIRSTNAME":"rth","EMAIL":"tht@thuyj.com","ADDRESS":"ytju"},
{"FIRSTNAME":"trhy","EMAIL":"klo@pyu.com","ADDRESS":"trght"},
{"FIRSTNAME":"ghy","EMAIL":"ytj@uki.com","ADDRESS":"ukyk"}]
my_dict = {}
for x in my_list:
    for key, value in x.items():
        my_dict[key] = my_dict.get(key, []) + [value]

my_dict内容:

>>> my_dict
{'EMAIL': ['jahg@jh.com', 'tht@thuyj.com', 'klo@pyu.com', 'ytj@uki.com'], 'FIRST
NAME': ['barc', 'rth', 'trhy', 'ghy'], 'ADDRESS': ['gyuyj', 'ytju', 'trght', 'uk
yk']}

现在导入到csv文件:

with open("your_file", "w") as f:
    for key,value in my_dict.items():
        f.write("{}:{}".format(key, ",".join(value)))