1

I have created comprehension expression referring to this page converting stacked dataframe to specified dictionary format.

dict_data = [{'Construction': i, j: k} for (i, j), k in stacked.items()]   

I tried to incorporate OrderedDict referring to this page
Changing to below.

dict_data = [OrderedDict(('Construction': i, j: k) for (i, j), k in stacked.items())]

but I get invalid syntax error
Could anyone tell me how should I fix this expression to incorporate with OrderedDict?

Katsuya Obara
  • 903
  • 3
  • 14
  • 30

1 Answers1

2

Try to init the OrderedDict with tuples like:

dict_data = [OrderedDict((('Construction', i), (j, k))) for (i, j), k in stacked.items()]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    I think you have a hanging bracket. I like to use lists to improve readability `[OrderedDict([('Construction', i), (j, k)]) for (i, j), k in stacked.items()]` – Peter Gibson Oct 11 '18 at 03:54
  • @Stephan Rauch Thank you! It worked! What about following case? dict_data = [{'Category': i, 'Type':j, k:l} for (i, j, k),l in stacked.items()] – Katsuya Obara Oct 11 '18 at 04:22
  • 1
    It is the same. Instead of `{...}` use `OrderedDict(((..), (..)))` where each `..` is a key value pair. – Stephen Rauch Oct 11 '18 at 04:24