Iterate through list of dictionaries in python

Jose Ramon

I have a list of dictionaries in python with the following form:

[{'item_value': 0.1, 'date': datetime.datetime(2017, ...), 'item_index': 1.0}, 
{'item_value': 0.22, 'date': datetime.datetime(2016, ...), 'item_index': 0.1}, 
{'item_value': 0.21, 'date': datetime.datetime(2016, ...), 'item_index': 1.0}
 ,..., 
{'item_value': 1.03, 'date': datetime.datetime(2016, ...), 'item_index': 1.0}]

Variable item_index takes values: [0.0, 0.1, 0.2, ..., 1.0] while variable item_value values between [-1, 1]. I want to construct a numpy vector which contain all possible item_index with the most recent item_value using the date (by omitting duplicates with the same item_value and keeping the most recent ones).

I am using the proposed solution:

np.array([d["item_value"] for d in sorted(my_list, key=lambda x: x["date"]))}

I create a numpy vector which contain all item_values sorted concerning the date [1.03, 0.22, 0.21, 0.1] in the case of the example. However, I want to return a vector like the following example:

[0, 0.22, 0, 0, 0, 0, 0, 0, 0, 0.1]

Each position of vector to represent the 11 possible values for item_index and have as a value the most recent value of the item_value. How can I do so?

EDIT

One example can be:

[{'item_value': 0.0, 'date': datetime.datetime(2017, 10, 11, 13, 39, 36, 979000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2017, 10, 11, 13, 40, 2, 368000), 'item_index': 1.0}
{'item_value': -1.0, 'date': datetime.datetime(2017, 10, 23, 9, 35, 20, 741000), 'item_index': 1.0}
{'item_value': -1.0, 'date': datetime.datetime(2017, 10, 23, 9, 35, 41, 915000), 'item_index': 0.8}
{'item_value': 0.0, 'date': datetime.datetime(2017, 10, 23, 9, 36, 2, 763000), 'item_index': 0.5}
{'item_value': 0.0, 'date': datetime.datetime(2017, 10, 23, 11, 40, 22, 427000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2017, 11, 14, 7, 33, 9, 131000), 'item_index': 1.0}
{'item_value': 0.51, 'date': datetime.datetime(2017, 11, 15, 12, 50, 25, 14000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 19, 14, 15, 46, 761000), 'item_index': 1.0}
{'item_value': -0.49, 'date': datetime.datetime(2018, 1, 19, 14, 16, 30, 207000), 'item_index': 1.0}
{'item_value': -0.009000000000000005, 'timestamp': datetime.datetime(2018, 1, 19, 16, 32, 30, 631000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 19, 16, 33, 19, 509000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 19, 16, 44, 59, 483000), 'item_index': 1.0}
{'item_value': -0.33299999999999996, 'date': datetime.datetime(2018, 1, 19, 18, 13, 17, 67000), 'item_index': 1.0}
{'item_value': 1.0, 'date': datetime.datetime(2018, 1, 19, 18, 13, 48, 443000), 'item_index': 1.0}
{'item_value': -0.33299999999999996, 'date': datetime.datetime(2018, 1, 19, 18, 14, 22, 871000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 28, 11, 45, 48, 223000), 'item_index': 1.0}
{'item_value': 0.005000000000000003, 'timestamp': datetime.datetime(2018, 1, 28, 11, 46, 7, 481000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 28, 11, 46, 27, 845000), 'item_index': 1.0}
{'item_value': 0.0, 'date': datetime.datetime(2018, 1, 28, 11, 46, 50, 386000), 'item_index': 1.0}]
eguaio

A oneliner could be as follows:

indexes = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

my_filtered_lists = [sorted([d for d in my_list if d['item_index'] == i], 
                            key=lambda x: x["date"])
                        for i in indexes ]

result = [l[-1]['item_value'] if len(l)>0 else 0  for l in my_filtered_lists]

For each index you filter the list, and sort each filtered list as desired and get the item_value of the last element. If the data set is big enough, this could be a little memory demanding, since you are creating one extra list for each item_idex.

Tested with:

 my_list = [
{'item_value': 0.1, 'date': datetime.datetime(2017, 05, 01), 'item_index': 1.0}, 
{'item_value': 0.22, 'date': datetime.datetime(2016,05,01), 'item_index': 0.1}, 
{'item_value': 0.21, 'date': datetime.datetime(2017, 05, 01), 'item_index': 0.1},
{'item_value': 1.03, 'date': datetime.datetime(2016,05,01), 'item_index': 1.0}]

It returns: [0, 0.21, 0, 0, 0, 0, 0, 0, 0, 0, 0.1] wich I understand is the expected output.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Iterate through Python Flask/Jinja2 adjacency list

Iteration Through tuple of dictionaries in Python

Python: Dictionary with list of dictionaries

Python: How to copy a list of a dictionaries

Python - Error , iterating list of dictionaries

python iterate through binary file without lines

How to iterate through a list and while iterating, iterate through another list and replace values for upper list with inner list key value pairs

python need to iterate a list over a list of dicts

Python - Traverse list of dictionaries - Error as NoneType

Problems removing dictionaries from list in Python

parsing 3 lists into list of dictionaries in python

How can I iterate through this list with modular variables

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

Iterate Array/List in Python for Alpha Numeric

How to search through dictionaries?

Looping through list of lists in Python

Iterate through Python dictionary N items at a time for CSV writing

I can't iterate through my list, it just says "list indices must be integers or slices, not str"

Filter a list of dictionaries by keys with different value for each key in Python

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

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

Python Group and aggregate unidirectionally a list of dictionaries by multiple keys

How exactly does Python check through a list?

How to iterate over a list (splitted string) in Python - for x in string

Pandas Python convert list data in record to iterate row

How to make a for loop iterate a list and ask for input? PYTHON

Iterate through points in an arbitrary shape

Iterate through JSON and pass it to tokeninput

How to iterate through XML in Powershell?

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) 테스트

뜨겁다태그

보관