3

For a writerow of a csv.DictWriter, I need to fill a (part of a) dictionary to be empty. I found no immediate solution for it. Is there one?

Like with

fieldnames = ['first','last']

Pseudocode

row = fieldnames.fill(None)

Result

print(row)
['first':None,'last':None]

So that

destination.writerow(row)

results in

,
László
  • 3,914
  • 8
  • 34
  • 49

3 Answers3

8

This is really a natural for the built-in dict method fromkeys:

>>> dict.fromkeys('abcd',None)
{'a': None, 'c': None, 'b': None, 'd': None}
>>> dict.fromkeys(['first','last'],None)
{'last': None, 'first': None}

No need for a dict comprehension (2.7+) or a list comprehension at all.

5

This can be achieved with a simple dictionary comprehension:

{key: None for key in keys}

E.g:

>>> keys = ["first", "last"]
>>> {key: None for key in keys}
{'last': None, 'first': None}

Edit: Looks like dict.fromkeys() is the optimal solution:

python -m timeit -s "keys = list(range(1000))" "{key: None for key in keys}"
10000 loops, best of 3: 59.4 usec per loop
python -m timeit -s "keys = list(range(1000))" "dict.fromkeys(keys)"
10000 loops, best of 3: 32.1 usec per loop
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • So this little loop is no slower than `fromkeys` I overlooked before? – László Oct 03 '12 at 00:27
  • @László I forgot about ``fromkeys()`` - I imagine there is little to no difference - so I'd recommend you go for whatever is clearer. – Gareth Latty Oct 03 '12 at 00:28
  • A bit surprising I found no documentation on the `fromkeys` method. But it should get me there. Thanks. – László Oct 03 '12 at 00:36
  • @László It's there [in the docs](http://docs.python.org/library/stdtypes.html#dict.fromkeys). – Gareth Latty Oct 03 '12 at 00:56
  • My +1 as I consider a dictionary comprehension more readable and undestandable. Actually, I never needed `.fromkeys()` and I would have to check the doc to understand what it does. (On the other hand, it is quite old method, and other people may prefer it.) – pepr Oct 03 '12 at 18:13
0

Something like this?

>>> fieldnames = ['first', 'last']
>>> row = dict((h, None) for h in fieldnames)
>>> row
{'last': None, 'first': None}
>>>
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84