2

this is my actual code :

import csv

fb_catalog_dict = {
    "id":"",
    "title":"",
    "description":"",
    "availability":"",
    "condition":"",
    "price":"",
    "link":"",
    "image_link":"",
    "brand":"",
    "additional_image_link":"",
    "age_group":"",
    "color":"",
    "gender":"",
    "item_group_id":"",
    "google_product_category":"",
    "material":"",
    "pattern":"",
    "product_type":"",
    "sale_price":"",
    "sale_price_effective_date":"",
    "shipping":"",
    "shipping_weight":"",
    "size":"",
    "custom_label_0":"",
    "custom_label_1":"",
    "custom_label_2":"",
    "custom_label_3":"",
    "custom_label_4":"",
}



with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, fb_catalog_dict.keys())
    w.writeheader()
    w.writerow(fb_catalog_dict)

i want to same dictionary in csv in same order like fb_catalog_dict, problem is python create me csv file with diferent order filds, how can i fix this ?

3 Answers3

7

In CPython >= 3.6 this will work as written, because dicts are ordered now.

On any earlier Python version (or different implementations), you can use collections.OrderedDict. It does exactly what its name suggests.

You will have to slightly change your instantiation, because passing a dict to OrderedDict just preserves the order of the dict, but not the order in which you wrote it. So just make it a list of tuples, as recommended here.


Example code:

import csv
from collections import OrderedDict

fb_catalog_dict = OrderedDict([
    ("id", ""),
    ("title", ""),
    ("description", ""),
    ("availability", ""),
    ...
    ])

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, fb_catalog_dict.keys())
    w.writerow(fb_catalog_dict)

(Not sure what your header was defined as, so I left it out.)

Graipher
  • 6,891
  • 27
  • 47
1

Dictionaries are unordered. And given you only use the keys anyway, what you are doing can be achieved with a list. ie:

fb_catalog = [
    "id",
    "title",
    "description",
]

etc..

JSharm
  • 1,117
  • 12
  • 11
0

In Python dict is and unordered structure. There is no specific order in a dict. So the only way I see is to use a list of fields to be sure you always get them in the same order:

import csv

d = {'1':1,'2':2,'z':'z'} 

def fb_catalog_dict(fields_list,dict_object):
    return [dict_object[f] if f in dict_object else None for f in fields_list]

f = open('mycsvfile.csv', 'w',newline='')
writer = csv.writer(f)

for i in range(10):
    writer.writerow(get_values_from_dict(['z','1','2'],d))
f.close()

P.S> the example is for Python 3.x