Search code examples
pythonordereddictionary

Save an OrderedDict Object to a csv file


I have the following object that is an OrderedDict that I would like to export to csv.

OrderedDict([('AGG', 0.09888),
             ('BWX', 0.04886),
             ('DBC', 0.06046),
             ('EMB', 0.05899),
             ('HYG', 0.07954),
             ('IEF', 0.09933),
             ('LQD', 0.07909),
             ('MBB', 0.10442),
             ('MUB', 0.09408),
             ('PCY', 0.05172),
             ('RING', 0.0026),
             ('SHM', 0.03761),
             ('SHY', 0.11148),
             ('SPY', 0.07296)])

I'm using the .to_csv command but the error message says: "'collections.OrderedDict' object has no attribute 'to_csv'"

Do I need to convert it to a df or an np array?

Thanks


Solution

  • Solution

    My first choice will be using pandas because of it's simplicity from user-implementation perspective.

    import pandas as pd
    pd.DataFrame(d.items()).to_csv('test.csv', index=False)
    

    Alternate Solution

    However, if for some reason you DO NOT want to use pandas, then you could use the following implementation.

    Note: I am using the OrderedDict (d) from the Dummy Data section below.

    Create CSV file: test.csv

    # Create lines
    CSV_FILENAME = 'test.csv'
    lines = [','.join(list(map(str,items))) for items in d.items()]
    # Create csv file
    with open(CSV_FILENAME, 'w') as f:
        f.write('\n'.join(lines))
    

    Check file-output in test.csv

    # Check if csv file was properly created    
    with open(CSV_FILENAME, 'r') as f:
        s = f.read()
    
    print(s)
    

    Output

    # test.csv
    
    AGG,0.09888
    BWX,0.04886
    DBC,0.06046
    EMB,0.05899
    HYG,0.07954
    IEF,0.09933
    LQD,0.07909
    MBB,0.10442
    MUB,0.09408
    PCY,0.05172
    RING,0.0026
    SHM,0.03761
    SHY,0.11148
    SPY,0.07296
    

    Dummy Data

    from collections import OrderedDict
    
    d = OrderedDict([('AGG', 0.09888),
                 ('BWX', 0.04886),
                 ('DBC', 0.06046),
                 ('EMB', 0.05899),
                 ('HYG', 0.07954),
                 ('IEF', 0.09933),
                 ('LQD', 0.07909),
                 ('MBB', 0.10442),
                 ('MUB', 0.09408),
                 ('PCY', 0.05172),
                 ('RING', 0.0026),
                 ('SHM', 0.03761),
                 ('SHY', 0.11148),
                 ('SPY', 0.07296)])