0

So I want to copy all keys from one dictionary into another, and initialize it with an empty list:

filtered_result = {}
for key in result.keys():
    filtered_result[key] = []

So I tried a more elegant way to do the same:

filtered_result = {}
filtered_result.fromkeys(result.keys(), [])

But the second way doesn't seem to work. What am I doing wrong?

Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
  • `filtered_result = dict.fromkeys(result.keys(), [])` – Konstantin Aug 24 '15 at 19:12
  • 3
    @Alik: no, because that'll **reuse** the same list object for all values. Perroloco, the correct expression is `filtered_result = {k: [] for k in result}`. Note that there is *no need to call `dict.keys()` here*, iterate directly over the dictionary and save yourself a method call and creation of another object where none is needed. – Martijn Pieters Aug 24 '15 at 19:13
  • 1
    @Perroloco: you didn't specify *in what way* it doesn't work. You'll increase your chances of getting a good answer if you do (and maybe even provide an example). – Snild Dolkow Aug 24 '15 at 19:15

0 Answers0