VBAtoPython

VBA Dictionary to Python dict

The VBA Scripting.Dictionary object is one of the most powerful tools in an Excel developer's arsenal. In Python, this functionality is built directly into the language as the dict type, which is faster, more flexible, and doesn't require external COM objects.

VBA Dictionary Example

VBA

Dim d As Object
Set d = CreateObject("Scripting.Dictionary")

' Adding items
d.Add "A", 100
d.Add "B", 200

' Checking existence
If d.Exists("A") Then
    Debug.Print d("A") ' Access by key
End If

Python dict Equivalent

Python

# Native dict creation
d = {"A": 100, "B": 200}

# Key assignment
d["C"] = 300

# Checking existence
if "A" in d:
    print(d["A"])  # Value access

Common VBA → Python Mappings

VBA Scripting.DictionaryPython dict
dict.Add k, vd[k] = v
dict.Exists(k)k in d
dict.Remove(k)del d[k]
dict.Keysd.keys()
dict.Itemsd.values()
For Each k In dict.Keysfor k in d:

Loop Conversion Example

VBA (Keys only)

Dim key As Variant
For Each key In d.Keys
    Debug.Print key, d(key)
Next key

Python (Items & Keys)

for key, value in d.items():
    print(key, value)

Important Differences

  • COM Helper vs Native Type: VBA requires CreateObject("Scripting.Dictionary") which adds overhead. Python dicts are built-in and highly optimized C implementations.
  • Insertion Order: In Python 3.7+, dictionaries are guaranteed to maintain insertion order. VBA Dictionaries also maintain order, but this is a happy accident of implementation rather than a strict guarantee in all versions.
  • Error Handling: Accessing a missing key in VBA (val = d("missing")) might inadvertently add it (if empty) or return Empty. In Python, d["missing"] raises a KeyError unless you use d.get("missing").

Have a full VBA module using Dictionaries?

Paste it into the converter and get a Python version instantly.