1

Firslty, I tried to search google for answer, but it turns to be hard to find a good answer since I'm python newbie.

I want to put some values from one dictionary into csv format. It sounds easy for all values:

import csv
import sys
mydictionary = {"one" : "1", "two" : 2, "three" : "3"}
w = csv.writer(sys.stderr)
w.writerow(mydictionary.values())

but what if I want to display only "one" and "three" values?. The next question is, why numbers are displayed "3,2,1" order, not in "1,2,3" order?

GoDaddyGo
  • 167
  • 3
  • 11
  • 2
    possible duplicate of [Why is python ordering my dictionary like so?](http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so) and also related : http://stackoverflow.com/questions/3420122/python-filter-dict-to-contain-only-certain-keys – Ashwini Chaudhary Jun 19 '13 at 10:22
  • 1
    You unfortunately asked *two* questions in one post; one of those is a duplicate. The other can best be solved using `csv.DictWriter()` instead of the regular writer; check out the [documentation](http://docs.python.org/2/library/csv.html#csv.DictWriter). – Martijn Pieters Jun 19 '13 at 10:34

3 Answers3

3

you can create a sub-dictionary by doing something like this:

subkeys = ["one", "three"]
subdict = {x: mydictionary[x] for x in mydictionary if x in subkeys}

print subdict

{'one': '1', 'three': '3'}

Dictionaries are not ordered structures in Python, so the order in which you enter keys doesn't necessarily have any bearing on the order in which they're retrieved. It might be the same, the reverse, or something else if operations have been applied to the dictionary in the interim. Have a look at Ordered Dictionaries if you really need the order to remain unchanged.

richsilv
  • 7,993
  • 1
  • 23
  • 29
0

You would be better off using the csv.DictWriter() class; it allows you to specify the order of the columns, and pick out only certain keys:

mydictionary = {"one" : "1", "two" : 2, "three" : "3"}
w = csv.DictWriter(sys.stderr, fields=('one', 'three'), extrasaction='ignore')
w.writerow(mydictionary)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

When working with dictionary where order is important, you might use and OrderedDict instead of a plain dict:

>>> mydictionary = collections.OrderedDict()
>>> mydictionary["one"]=1
>>> mydictionary["two"]=2
>>> mydictionary["three"]=3
>>> mydictionary
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125