简体   繁体   中英

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 :

{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()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM