Extract all keys from a list of dictionaries

前端 未结 6 777
遇见更好的自我
遇见更好的自我 2020-12-08 03:58

I\'m trying to get a list of all keys in a list of dictionaries in order to fill out the fieldnames argument for csv.DictWriter.

previously, I had something like thi

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 04:32

    Borrowing lis from @AshwiniChaudhary's answer, here is an explanation of how you could solve your problem.

    >>> lis=[
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5, "height":4},
    {"name": "Pam", "age": 7, "weight":90}
    ]
    

    Iterating directly over a dict returns its keys, so you don't have to call keys() to get them back, saving a function call and a list construction per element in your list.

    >>> {k for d in lis for k in d}
    set(['age', 'name', 'weight', 'height'])
    

    or use itertools.chain:

    >>> from itertools import chain
    >>> {k for k in chain(*lis)}
    set(['age', 'name', 'weight', 'height'])
    

提交回复
热议问题