How to quickly convert from items in a list of lists to list of dictionaries in python?

Setsuna

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.

murgatroid99

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Lambda to count total items in a list of lists

convert str to list in python

Iterate through list of dictionaries in python

keeping certain dates from list of dictionaries

Python: How to create a csv string (no file) from a list of dictionaries?

How to get integer from list of lists

Python: How to copy a list of a dictionaries

How to compare the index of 2 sublists' elements from a list of lists

Python Convert a list into a dataframe

Divide list and append the list to separate lists python

Get all keys from a list of dictionaries

Storing items in a list for python

Python list to list of lists

Python how to strip a string from a string based on items in a list

How to extract tuples from a list of lists in Haskell

Python - How to delete the last element in a list of lists?

Problems removing dictionaries from list in Python

Python: Dictionary with list of dictionaries

Convert a dictionary of strings and lists to a list of lists

Convert dictionary containing items and counts to list of items

How to convert a list of lists of lists into a list of lists?

Convert comma separated string to list items in Python

How to sort a large list of dictionaries without loading into memory in Python

The best way to convert python list items from string to number

Looping through list of lists in Python

parsing 3 lists into list of dictionaries in python

How to convert a Python string in a list using no libraries

Python - Error , iterating list of dictionaries

Removing spaces from multiple string items in a list in python