简体   繁体   English

阅读字典并写入文本文件

[英]Read Dictionary and write to a text file

I have a dictionary now: 我现在有字典:

data = [{'position': 1, 'name':'player1:', 'number': 524}, {'position':2, 'name': 'player2:','number': 333}]

(just list two group of number first to simplify the problem) I want to read and print it in the order of positions: "position 1", "position 2" ... "position n" in a text or csv file. (首先列出两个数字组以简化问题)我想按以下位置顺序阅读和打印:文本或csv文件中的“位置1”,“位置2” ...“位置n”。

something like: 就像是:

position    name      number
1           player1    524
2           player2    333

I tried: 我试过了:


data = [{'position': 1, 'name':'player1', 'number': 524}, {'position':2, 'name': 'player2:','number': 333}]

keys = data[0].keys()

with open(output.csv", 'r') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data)

Seems like I should create a csv instead of open it first. 似乎我应该创建一个csv而不是先打开它。 Also, is there any better ways? 另外,还有什么更好的方法吗? Thanks. 谢谢。

The easiest thing to do would probably be to read it into a pandas Dataframe and then write it to a csv. 最简单的操作可能是将其读取到pandas Dataframe中,然后将其写入csv。

import pandas as pd

data = [
    {
        'position': 1,
        'name':'player1',
        'number': 524
    }, {
        'position': 2,
        'name': 'player2',
        'number': 333
    }
]

df = pd.DataFrame.from_records(data, columns=['position', 'name', 'number'])
df = df.sort_values('position')
df.to_csv('data.csv')

use pandas 使用熊猫

import pandas as pd
data = [
         {
           'position': 1,
           'name':'player1:',
           'number': 524
         }, {
           'position':2,
           'name':'player2:',
           'number': 333
         }
       ]
df = pd.DataFrame.from_records(data, columns=['position', 'name', 'number'])
df = df.sort_values('position')
df.head()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM