[英]transform dict with nested array values
I have the example data below, which is a default dictionary. 我在下面有示例数据,这是默认词典。 I'm trying to transform it in to a dictionary like the desired output below, but I'm having trouble getting the keys to match the keys from the original dictionary. 我正在尝试将其转换为字典,如下面所需的输出,但是我在获取与原始字典中的键相匹配的键时遇到了麻烦。 I can get the values using the code below. 我可以使用下面的代码获取值。 Any tips are greatly appreciated. 任何提示,不胜感激。
Code: 码:
res[0].item()
Output: 输出:
-1.613331913948059
Example data: 示例数据:
res
defaultdict(<function __main__.<lambda>>,
{0: array([-1.6133319], dtype=float32),
1: array([-1.278326], dtype=float32),
2: array([-0.68584293], dtype=float32),
3: array([-1.2741858], dtype=float32),
4: array([-0.81194735], dtype=float32)})
Desired output: 所需的输出:
{0: -1.6133319,
1: -1.278326,
2: -0.68584293,
3: -1.2741858,
4: -0.81194735}
IIUC, This dictionary comprehension should do the trick : IIUC,这个字典理解应该可以解决这个问题:
{k:v[0] for k,v in res.items()}
{0: -1.6133319, 1: -1.278326, 2: -0.68584293, 3: -1.2741858, 4: -0.81194735}
以下为我工作:
{k: res[k].item() for k in res}
This seems to have done the trick 这似乎已经成功了
test_res={}
for ids in list(res.keys()):
test_res[ids]=res[ids].item()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.