How to remove last two element from each sublists in dict

Question:

Is it possible to remove all elements expect first one from each sublists which is act as a value in dict without using any loop

let d =

 [
    { "x":1640995200000, "y": [2365,2567.300049,2305,2386.600098] },
    { "x":1643673600000, "y": [2408,2456.399902,2243,2359.550049] },
    { "x":1646092800000, "y": [2359.550049,2688,2180,2634.750000] }
]

output =

 [
    { "x":1640995200000, "y": 2365 },
    { "x":1643673600000, "y": 2408 },
    { "x":1646092800000, "y": 2359.550049 }
]
Asked By: Ujjal Modak

||

Answers:

Assume that the lists have at least one element in each.

d = [{"x":item["x"], "y": item["y"][0]} for item in d]

More about list comprehension could be found here https://www.w3schools.com/python/python_lists_comprehension.asp

Answered By: TaQuangTu

Using an explicit loop of some kind will make it clearer to the reader / maintainer what you’re trying to do. However, if you really want to obfuscate the process then you could do this:

d = [
    { "x":1640995200000, "y": [2365,2567.300049,2305,2386.600098] },
    { "x":1643673600000, "y": [2408,2456.399902,2243,2359.550049] },
    { "x":1646092800000, "y": [2359.550049,2688,2180,2634.750000] }
]

output = list(map(lambda _d: {'x': _d['x'], 'y': _d['y'][0]}, d))

print(output)

Output:

[{'x': 1640995200000, 'y': 2365}, {'x': 1643673600000, 'y': 2408}, {'x': 1646092800000, 'y': 2359.550049}]
Answered By: Fred
import pandas as pd
df = pd.DataFrame(d)
df['y'] = df['y'].apply(lambda x: x[0])
df.to_dict('records')
Answered By: Barot Mahima
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.