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 IfPython 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 accessCommon VBA → Python Mappings
| VBA Scripting.Dictionary | Python dict |
|---|---|
| dict.Add k, v | d[k] = v |
| dict.Exists(k) | k in d |
| dict.Remove(k) | del d[k] |
| dict.Keys | d.keys() |
| dict.Items | d.values() |
| For Each k In dict.Keys | for 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 keyPython (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 aKeyErrorunless you used.get("missing").
Have a full VBA module using Dictionaries?
Paste it into the converter and get a Python version instantly.