1

Could you give me some advice about parsing list from list of dictionary with some conditions in Python3.

From below list of json, I want to extract the max timestamp for each "id".

So the final output I want to have is like

[{
    "id": 1,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600957822.2510917
},
{
    "id": 2,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600958083.618805
}]

Is there any way I can do? Thanks in advance

[
{
    "id": 1,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600957822.2510917
},
{
    "id": 2,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600957857.3018847
},
{
    "id": 2,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600958027.4114041
},
{
    "id": 2,
    "value": {
        "val1": 400000000,
        "val2": 750000000
    },
    "timestamp": 1600958083.618805
}]
1
  • This has nothing to do with JSON, it's just looping through a list of dictionaries. The fact that the list came from parsing JSON is irrelevant. Commented Sep 24, 2020 at 16:17

2 Answers 2

1

If it's list of dictionaries (as spotted in the comments) here is a way to parse it and retrieve a final list of dict:

result = {}
for obj in dict_list:
    if obj['id'] in result:
        if result[obj['id']]['timestamp'] < obj['timestamp']:
            result[obj['id']]['timestamp'] = obj['timestamp']
    else:
        result[obj['id']] = obj
[x for x in result.values()]
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example of parsing:

import json

# load json
data = json.loads(source)

result = {}

# iterate over json objects
for d in data:
    # check whether id is already in result map or not
    if d['id'] in result:
        # if id already in result, compare timestamps
        if d['timestamp'] > result[d['id']]:
            result[d['id']] = d['timestamp']
    else:
        # if id not in result, add id / timestamp pair
        result[d['id']] = d['timestamp']
    
print (result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.