Dictionary Syntax#
Note
Source: Adapted from the C# edition (dictionaries/dictionarysyntax.rst).
Python’s dict replaces C#’s Dictionary<K,V>. No type annotation
is needed in the declaration. Python dicts preserve insertion order
(guaranteed since Python 3.7) and use key in d in place of
ContainsKey.
A dictionary maps keys to values. Given a key, you can look up its associated value in constant time — like looking up a word in a reference book.
Creating Dictionaries#
Use braces with key: value pairs:
e2sp = {"one": "uno", "two": "dos", "three": "tres"}
word_count = {} # empty dict
ages = {"Alice": 30, "Bob": 25}
You can also use dict() with keyword arguments:
e2sp = dict(one="uno", two="dos", three="tres")
Accessing and Modifying Entries#
Use square brackets to get or set a value by key:
print(e2sp["one"]) # "uno"
e2sp["four"] = "cuatro" # add new entry
e2sp["two"] = "DOS" # update existing entry
Accessing a key that does not exist raises a KeyError. Use
dict.get(key, default) to avoid the exception:
print(e2sp.get("five", "not found")) # "not found"
print(e2sp.get("one", "not found")) # "uno"
Membership Test#
Use in to test whether a key is present (replaces C#’s ContainsKey):
print("three" in e2sp) # True
print("seven" in e2sp) # False
Removing Entries#
del d[key]removes the entry (raisesKeyErrorif absent).d.pop(key)removes and returns the value; accepts an optional default.d.clear()removes all entries.
del e2sp["two"]
removed = e2sp.pop("three", None)
print(len(e2sp)) # number of remaining entries
Iterating Over a Dictionary#
e2sp = {"one": "uno", "two": "dos", "three": "tres"}
for key in e2sp: # iterate over keys (insertion order)
print(key, "->", e2sp[key])
for key in e2sp.keys(): # explicit keys view
print(key)
for val in e2sp.values(): # values view
print(val)
for key, val in e2sp.items(): # key-value pairs
print(f"{key}: {val}")
Output of the last loop:
one: uno
two: dos
three: tres
Key Type Restriction#
Dictionary keys must be immutable — strings, numbers, and tuples are valid keys; lists are not. This restriction exists because of how hash tables work (see Dictionary Efficiency).