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

Siddhesh Bhurke 46 Reputation points
2021-04-13T14:24:43.43+00:00
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
Azure Databricks
An Apache Spark-based analytics platform optimized for Azure.
1,940 questions
{count} votes

Accepted answer
  1. MartinJaffer-MSFT 26,031 Reputation points
    2021-04-13T17:58:59.727+00:00

    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 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. MartinJaffer-MSFT 26,031 Reputation points
    2021-04-13T17:07:09.807+00:00

    Hello @Siddhesh Bhurke 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))