简体   繁体   中英

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.

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. 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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