Assuming I have the following structure:
listoflist = [[0,1,2,3,4],[2,4,2,3,4],[3,4,5,None,3],...]
Assuming I have:
headers = ["A","B","C","D","E"]
I want to convert each to:
listofobj = [{"A":0,"B":2,"C":3,"D":4,"E":5},{"A":2,"B":4,"C":2,"E":4}]
What is the best way to do this?
Note that D: does not show up for the 3rd dictionary in the converted list because it is None. Am looking for the most optimal way/quickest performance for this.
You can use list comprehension to perform an operation on each element of a list, the zip
builtin function to match each element of headers
against the corresponding element in listoflist
, and the dict
builtin function to convert each of those into a dictionary. So, the code you want is
listofobj = [dict(zip(headers, sublist)) for sublist in listoflist]
Removing None
values is probably best done in another function:
def without_none_values(d):
return {k:d[k] for k in d if d[k] is not None}
With that function, we can complete the list with
listofobj = [without_none_values(dict(zip(headers, sublist))) for sublist in listoflist]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다