I want to convert the following nested dictionary into a nested list of lists with List Comprehension method for better performance:
n = {
"ETHBTC": {
"2021-09-04 01:55:00": {
"open": 0.078998,
"close": 0.079007,
"volume": 44.952200000000005
},
"2021-09-04 01:56:00": {
"open": 0.079005,
"close": 0.078959,
"volume": 68.62790000000001
},
"2021-09-04 01:57:01": {
"open": 0.07896,
"close": 0.078962,
"volume": 131.6615000000001
},
"2021-09-04 01:58:00": {
"open": 0.078966,
"close": 0.078988,
"volume": 157.38520000000005
}
}
"BTCUSDT": {
"2021-09-04 01:55:00": {
"open": 49730.55,
"close": 49710.01,
"volume": 28.57857999999999
},
"2021-09-04 01:56:00": {
"open": 49710.0,
"close": 49681.35,
"volume": 19.088980000000017
},
"2021-09-04 01:57:00": {
"open": 49681.36,
"close": 49737.05,
"volume": 20.885500000000008
},
"2021-09-04 01:58:00": {
"open": 49737.06,
"close": 49757.33,
"volume": 35.782369999999965
}
}
Expected output to be with let say with the "close" value i am trying to do this in one liner code for better efficiency:
result = ["ETHBTC"[0.079007, 0.078959, 0.078962, 0.078988],
"BTCUSDT"[49710.01, 49681.35, 49737.05, 49757.33]]
CodePudding user response:
Just because there's less code on the screen doesn't mean it's more efficient. Along with that, if transforming data down means losing meaningful data then it is superfluous to the grand scheme. Also python is not about starting with efficiency but with functionality. After that you can revisit and improve upon bottlenecks/etc...
That said I can see the need to do this, and yes probably one of the most efficient and readable ways to do this would be a one line snippet of code. Please refer to The Zen of Python as it works out that it refers to what I just said.
But why a list? Isn't a hash table/lookup more efficient than a list of unique key'd dict's?
Finally I leave you with what is, my mind, the correct way to implement your expected output. But consider my thoughts above.
>>> {k: [d['close'] for d in v.values()] for k, v in n.items()}
{"ETHBTC": [0.079007, 0.078959, 0.078962, 0.078988],
"BTCUSDT": [49710.01, 49681.35, 49737.05, 49757.33]}
If you must have a list of dict's you can easily modify the above code to achieve the desired result:
>>> [{k: [d['close'] for d in v.values()]} for k, v in n.items()]
[{"ETHBTC": [0.079007, 0.078959, 0.078962, 0.078988]},
{"BTCUSDT": [49710.01, 49681.35, 49737.05, 49757.33]}]
FYI: Before asking someone especially this site a question it should behoove you to attempt to find the answer yourself or attempt to find it.