question

SiddheshBhurke-0549 avatar image
0 Votes"
SiddheshBhurke-0549 asked SiddheshBhurke-0549 commented

How to round and convert the nested values from dictionary to integer in Python?

 enc = {'Category': {'a1': 1885.4403010060062,
   'a2': 1072.0176453884112,
   'a3': 1448.579447138836,
   'a4': 1471.5656350474158,
   'a5': 1232.3527616505146,
   'a6': 891.9808067951503,
   'a7': 1378.9613179304858}}



I have tried this.


 for key, value in enc.items():
   for k,v in value.items():
     enc[value][k] = int(round(v))


I am getting this error:



 TypeError: Invalid argument, not a string or column: 1885.4403010060062 of type <class 'float'>. For column literals, use 'lit', 'array', 'struct' or 'create_map' function.

I am looking for a final output like:

 enc = {'Category': {'a1': 1885,
   'a2': 1072,
   'a3': 1448,
   'a4': 1471,
   'a5': 1232,
   'a6': 891,
   'a7': 1378}}

I am expecting the values to be rounded and then converted to integer.




azure-databricks
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@SiddheshBhurke-0549 are you still facing the issue? If my solution answered your question, please mark as accepted answer.

0 Votes 0 ·
MartinJaffer-MSFT avatar image
1 Vote"
MartinJaffer-MSFT answered SiddheshBhurke-0549 commented

Actually this works too:

 for outk, outv in enc.items():
 ...   for ink, inv in outv.items():
 ...     enc[outk][ink] = round(inv)

so looking at your original code

enc[value][k] = int(round(v))

The problem is you used value where you should have used key.



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for the update Martin.

I tried this since I am using python

 for key, value in enc.items():
     for k, v in value.items():
         enc[key][k] = np.rint(v).astype(int)
1 Vote 1 ·
MartinJaffer-MSFT avatar image
0 Votes"
MartinJaffer-MSFT answered MartinJaffer-MSFT commented

Hello @SiddheshBhurke-0549 and welcome to Microsoft Q&A.

Looks like you have an extra loop in there.

 for key,value in enc['Category'].items():
    enc['Category'][key] = int(round(value))
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hmm. actually looks like ours are really similar. Only difference is you iterating an extra layer. Hmm, any experts out there want to educate both of us with an explanation?

0 Votes 0 ·