输出到屏幕和csv格式python

2024-09-29 17:18:28 发布

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

我有一个python嵌套字典输出,我已经能够使用RocketDist删除第一组cruly括号,但是1)我无法删除第二组花括号2)我试图将其导出到一个提供列名的csv文件,但这不起作用,因为我不知道如何获取行中递增的int/#值。例如,这里是我的初始输出:

火箭发射前:

{ intx/x : {'value1: 'A', 'value2: 'B', value3: 'C'},
  inty/y : {'value1: 'X', 'value2: 'Y', value3: 'Z'}}

火箭发射后:

  intx/x : {'value1: 'A', 'value2: 'B', value3: 'C'},
  inty/y : {'value1: 'X', 'value2: 'Y', value3: 'Z'}

期望输出:

  intx/x : 'value1: 'A', 'value2: 'B', value3: 'C',
  inty/y : 'value1: 'X', 'value2: 'Y', value3: 'Z'

csv的所需输出:

CSV Sample

以下是完整的脚本:

results = requests.get(url, headers=headers)
inventory = results.json()
data = inventory['config']

class RocketDict(UserDict):
    def __str__(self):
        r = ['']
        r.extend(['\t{} : {}'.format(k, v)
            for k, v in self.items()])
        return ',\n'.join(r)

if __name__ == '__main__':
#standard dict object
#    inventory = {('key-%02d' % v): v for v in range(1, 10)}
#    print(inventory, '\n')
# Wrap that dict object into a RocketDict.
    d2 = RocketDict(data)
    print(d2)

csv_columns = ['value1','value2','value3']
dict_data = d2
csv_file = 'mycsv.csv'
try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        writer.writeheader()
        for data in dict_data:
            writer.writerow(d2)
except IOError:
    print("I/O error")

Tags: csvinfordatadictwriterd2inventory
1条回答
网友
1楼 · 发布于 2024-09-29 17:18:28

使用熊猫-

RocketDict ={ 'intx/x' : {'value1': 'A', 'value2': 'B', 'value3': 'C'},
    'inty/y' : {'value1': 'X', 'value2': 'Y', 'value3': 'Z'}}
import pandas as pd
pd.DataFrame(RocketDict).transpose().to_csv('out.csv', index =True)

相关问题 更多 >

    热门问题