Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fill a dict with None for all keys (given in a list) in Python 3.3 [duplicate]

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

,
like image 680
László Avatar asked Sep 18 '25 00:09

László


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!