0

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}

3 Answers 3

1

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}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for getting back to me so quickly, that worked.
1

The following worked for me:

{k: res[k].item() for k in res}

Comments

0

This seems to have done the trick

test_res={}

for ids in list(res.keys()):
  test_res[ids]=res[ids].item()

1 Comment

Even though this works, it will be slower than a dict comprehension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.