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리뷰
로그인참여 후 검토

관련 기사

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

parsing 3 lists into list of dictionaries in python

Python: How to copy a list of a dictionaries

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

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

Problems removing dictionaries from list in Python

Python list to list of lists

Convert comma separated string to list items in Python

Python: Dictionary with list of dictionaries

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

How to get integer from list of lists

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

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

Iterate through list of dictionaries in python

Python - Error , iterating list of dictionaries

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

Convert dictionary containing items and counts to list of items

Storing items in a list for python

Lambda to count total items in a list of lists

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

Divide list and append the list to separate lists python

keeping certain dates from list of dictionaries

Get all keys from a list of dictionaries

Looping through list of lists in Python

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

Removing spaces from multiple string items in a list in python

convert str to list in python

Python Convert a list into a dataframe

TOP 리스트

  1. 1

    Ionic 2 로더가 적시에 표시되지 않음

  2. 2

    JSoup javax.net.ssl.SSLHandshakeException : <url>과 일치하는 주체 대체 DNS 이름이 없습니다.

  3. 3

    std :: regex의 일관성없는 동작

  4. 4

    Xcode10 유효성 검사 : 이미지에 투명성이 없지만 여전히 수락되지 않습니까?

  5. 5

    java.lang.UnsatisfiedLinkError : 지정된 모듈을 찾을 수 없습니다

  6. 6

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  7. 7

    상황에 맞는 메뉴 색상

  8. 8

    SMTPException : 전송 연결에서 데이터를 읽을 수 없음 : net_io_connectionclosed

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    Windows cmd를 통해 Anaconda 환경에서 Python 스크립트 실행

  11. 11

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  12. 12

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  13. 13

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  14. 14

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  15. 15

    복사 / 붙여 넣기 비활성화

  16. 16

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  17. 17

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  18. 18

    SQL Server-현명한 데이터 문제 받기

  19. 19

    Seaborn에서 축 제목 숨기기

  20. 20

    ArrayBufferLike의 typescript 정의의 깊은 의미

  21. 21

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

뜨겁다태그

보관