Python code error KeyError:<Autodsk.Revit.DB.ForgeTypeId

How should I solve the above problem?

your input ā€œunittoconvertā€ seems not to be a string, but a forgetype. you can therefore not find that as a key in your dictionary.

see if OUT=type(unittoconvert) returns a string.

if not, you could try to convert it to a string and then query your dictionary.

1 Like

Try using the UnitUtils.Convert() method like this:

  • Revit >= 2022
    newvalue = UnitUtils.Convert(oldvalue, UnitTypeId.FeetFractionalInches, UnitTypeId.Meters)
  • Revit < 2022
    newvalue = UnitUtils.Convert(oldvalue, DisplayUnitType.DUT_FRACTIONAL_INCHES, DisplayUnitType.DUT_METERS)

So in your case something like
OUT = UnitUtils.Convert(1.0, UnitTypeId.Feet, IN[0])

[Edit] TIL thereā€™s a unit called a slug - lol
image

# Load the Python Standard and DesignScript Libraries
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
#imports the Revit API
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *

#sets the distance to convert as input 0
originalUnit = IN[0]
unitToConvert = IN[1]

#builds a hard coded list of dictionary values for the conversion factors
conversionToFeet = {
        "DUT_METERS":1/3.28084,
        "DUT_METERS_CENTIMETERS": 1/3.28084,
        "DUT_MILLIMETERS" : 304.8,
        "DUT_CENTIMETERS" : 30.48,
        "DUT_DECIMAL_FEET" : 1,
        "DUT_FEET_FRACTIONAL_INCHES": 1,
        "DUT_DECIMAL_INCHES" : 1/12.0,
        "DUT_FRACTIONAL_INCHES" : 1/12.0
}

newvalue = UnitUtils.Convert(oldvalue, UnitTypeId.FeetFractionalInches, UnitTypeId.Meters)

originalUnitInFeet = 1/conversionToFeet[originalUnit]

convertedUnit = originalUnitInFeet * conversionToFeet[unitToConvert]
convertedUnit = round(convertedUnit,10)

# return the converted length value
OUT = UnitUtils.Convert(1.0, UnitTypeId.Feet, IN[0])

Is that right?
but it But if you write the code like this
An error appears that the old value is not defined

line 30
NameError:name ā€˜oldvalueā€™ is not defined