Home > OS >  Changing the order of keys in a list of dictionaries with TypeError?
Changing the order of keys in a list of dictionaries with TypeError?

Time:03-29

I have a dictionary

dicts = [{'date':2018, 'target':'usd'}, {'date':2020, 'target':'eur'}, {'date':2019, 'target':'eur'}]

I want to rearrange the order of the keys like this:

[{'target':'usd','date':2018}, { 'target':'eur','date':2020}, {'target':'eur',date':2019}]

I have tried this but am getting an error in my python 3.9:

key_order = [ 'target', 'date']
dicts = {k : dicts[k] for k in key_order}
dicts

TypeError: list indices must be integers or slices, not str

thank you.

CodePudding user response:

dicts is a list, not a dictionary. as the error message states.

this may work:

dicts = [{k: dct[k] for k in key_order} for dct in dicts]

you need the dict-comprehension inside a list-comprehension.

you need at least python 3.6 for this to work. before that version dicts werde not insertion-ordered.

  • Related