Given an OrderedDict
d
, I'd like to convert a nested for
loop to a list comprehension. The OrderedDict
d
looks like this:
import collections
import numpy as np
d = collections.OrderedDict(
[
(
60.0,
{
Timestamp('2016-03-24 00:00:00'): np.nan,
Timestamp('2016-03-11 00:00:00'): 2.0173333333333336,
Timestamp('2016-02-19 00:00:00'): np.nan,
Timestamp('2016-02-26 00:00:00'): np.nan,
Timestamp('2016-03-04 00:00:00'): np.nan,
Timestamp('2016-03-18 00:00:00'): np.nan,
Timestamp('2016-04-01 00:00:00'): np.nan
}
), (
65.0,
{
Timestamp('2016-03-24 00:00:00'): np.nan,
Timestamp('2016-03-11 00:00:00'): np.nan,
Timestamp('2016-02-19 00:00:00'): np.nan,
Timestamp('2016-02-26 00:00:00'): np.nan,
Timestamp('2016-03-04 00:00:00'): 1.8621538461538463,
Timestamp('2016-03-18 00:00:00'): np.nan,
Timestamp('2016-04-01 00:00:00'): np.nan
}
)
]
)
You'll notice there are unordered dicts as values. My goal is to order the "internal" dicts by timestamp, the return the values of the "internal" dict. Finally, I need to combine the key of the "internal" dicts with the values. Result should look like this:
[
[60.0, nan, nan, nan 2.0173333333333336, nan, nan, nan],
[65.0, nan, nan, 1.8621538461538463, nan, nan, nan, nan]
]
The following code prints this out nicely and I want to avoid appending to a list:
for k,v in d.iteritems():
od = collections.OrderedDict(sorted(v.items()))
for k_, v_ in od.iteritems():
print k, k_, v_
I've also tried the following but it does not sort by key:
for row in [[k] + sorted(v.values()) for k, v in d.iteritems()]:
print row
Therefore, looking to convert this to a list comprehension.
[[k] + [v_[1] for v_ in sorted(v.items())] for k,v in d.iteritems()]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.