'Changing the order of keys in a list of dictionaries with TypeError?
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
