1

Is it possible (and, more importantly, practical) to write the following code as a dict comprehension?

I am creating a dictionary here and then checking for "blank" values (represented by a '-') and replacing it with another string value.

test_dict = dict(zip(list_one,list_two))
for k,v in test_dict.items():
    if v == '-':
        test_dict[k] = 'missing'

1 Answers1

2

Why not do the replacement when you are creating the dictionary?

test_dict = dict(zip(list_one, 
                     ('missing' if x == '-' else x for x in list_two)))

Or, if you have an existing dictionary you can create a new one using:

{k: 'missing' if v == '-' else v for k, v in d.items()}

If you wish to alter the existing dictionary in-place then really there is nothing wrong with the existing code. You could use a list comprehension such as:

[d.__setitem__(k, 'missing') for k, v in d.items() if v == '-']

but that is rather ugly.

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • it is not just ugly, there you are playing with mutability in a comprehension, building a completly useless list in memory which can be eventually huge. – Netwave Jun 18 '17 at 09:49
  • @DanielSanchez Clearly ... as I said, ugly. (size isn't really an issue, this could be done with an equally ugly `any(...)` wrapped around it to avoid that) – donkopotamus Jun 18 '17 at 09:50
  • Thanks so much @donkopotamus I like the first suggestion. – Racchit Thapliyal Jun 18 '17 at 23:37