Home > Mobile >  How to get make a list of key names from a list of dictionaries in Python
How to get make a list of key names from a list of dictionaries in Python

Time:11-02

I have a list of dictionaries that I'm taking from a .cvs file, for example:

[{'name': 'Tom', 'Age': '15', 'location': 'USA'}, 
{'name': 'Paul', 'Age': '31', 'location': 'UK'},
{'name': 'Tony', 'Age': '24', 'location': 'France'}
]

Now say I didn't know what the names of the different keys were, how would I create a list of them, as per my example, specifically a list of ['name', 'age', 'location']? Thanks.

CodePudding user response:

values_of_key = [key for a_dict in list_of_dicts for key in a_dict.keys()]
values_of_key = list(dict.fromkeys(values_of_key))

CodePudding user response:

Thanks to Thierry Lathuille for the pointers, I actually figured out 2 different ways to do it, I can either use the csv.fieldname attribute while I have the file open as Thierry recommended, or I can use file[0].keys() from the completed list as keys will be the same for all entries.

  • Related