簡體   English   中英

閱讀字典並寫入文本文件

[英]Read Dictionary and write to a text file

我現在有字典:

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

(首先列出兩個數字組以簡化問題)我想按以下位置順序閱讀和打印:文本或csv文件中的“位置1”,“位置2” ...“位置n”。

就像是:

position    name      number
1           player1    524
2           player2    333

我試過了:


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)

似乎我應該創建一個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')

使用熊貓

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