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 }
]
CodePudding user response:
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}]
CodePudding user response:
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