Syntax ⧉ Copy d = { key: value, ...}
d = dict ( key= value, ...) Example ⧉ Copy user = { "name" : "Alice" , "age" : 30 , "active" : True }
from_pairs = dict ( host= "localhost" , port= 8080 )
print ( user)
print ( from_pairs) Output {'name': 'Alice', 'age': 30, 'active': True}
{'host': 'localhost', 'port': 8080}Note Keys must be hashable (strings, numbers, tuples of hashables). Lists and dicts cannot be keys.
create dictionary new dict key value pair initialize dict
Accessing & Modifying Values Syntax ⧉ Copy d[ key]
d[ key] = valueExample ⧉ Copy config = { "debug" : False , "port" : 3000 }
print ( config[ "port" ])
config[ "debug" ] = True
config[ "host" ] = "0.0.0.0"
print ( config) Output 3000
{'debug': True, 'port': 3000, 'host': '0.0.0.0'}Note Accessing a missing key with d[key] raises KeyError. Use d.get(key) to safely return None instead.
get dict value set dict value access dictionary update dictionary
Syntax ⧉ Copy d. get ( key, default) Example ⧉ Copy settings = { "theme" : "dark" }
theme = settings. get ( "theme" , "light" )
lang = settings. get ( "language" , "en" )
print ( theme, lang) Output dark enNote get() returns the default when the key is missing but does NOT add it to the dict. Use setdefault() if you want to also store the default.
get with default safe access dict missing key default setdefault
Syntax ⧉ Copy d. keys () / d. values () / d. items () Example ⧉ Copy scores = { "alice" : 95 , "bob" : 82 , "carol" : 91 }
print ( list ( scores. keys ()))
print ( list ( scores. values ()))
for name, score in scores. items () :
print ( f" { name} : { score} " ) Output ['alice', 'bob', 'carol']
[95, 82, 91]
alice: 95
bob: 82
carol: 91Note keys(), values(), and items() return view objects that reflect changes to the dict in real time.
dict keys dict values iterate dictionary loop over dict
Dictionary Comprehensions Syntax ⧉ Copy { key_expr: val_expr for item in iterable if condition} Example ⧉ Copy words = [ "hello" , "world" , "python" ]
lengths = { w: len ( w) for w in words}
print ( lengths)
original = { "a" : 1 , "b" : 2 , "c" : 3 }
filtered = { k: v for k, v in original. items () if v >= 2 }
print ( filtered) Output {'hello': 5, 'world': 5, 'python': 6}
{'b': 2, 'c': 3}Note Dict comprehensions are great for transforming or filtering dictionaries in a single expression.
Merging Dictionaries (| Operator) Syntax ⧉ Copy merged = d1 | d2
d1 |= d2 Example ⧉ Copy defaults = { "color" : "blue" , "size" : "medium" }
overrides = { "size" : "large" , "bold" : True }
final = defaults | overrides
print ( final) Output {'color': 'blue', 'size': 'large', 'bold': True}Note The | operator (Python 3.9+) creates a new dict. Right-hand side wins on duplicate keys. Use |= to merge in place.
merge dictionaries combine dicts union dict pipe operator dict
Syntax ⧉ Copy from collections import defaultdict
dd = defaultdict ( factory) Example ⧉ Copy from collections import defaultdict
word_count = defaultdict ( int )
for word in "the cat sat on the mat" . split () :
word_count[ word] += 1
print ( dict ( word_count)) Output {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}Note defaultdict auto-creates missing keys using the factory function. Common factories: int (0), list ([]), set (set()).
Syntax ⧉ Copy from collections import Counter Example ⧉ Copy from collections import Counter
letters = Counter ( "mississippi" )
print ( letters. most_common ( 3 ))
inventory = Counter ( apples= 5 , oranges= 3 )
inventory. update ( apples= 2 )
print ( inventory[ "apples" ]) Output [('s', 4), ('i', 4), ('p', 2)]
7Note Counter supports arithmetic: Counter('aab') - Counter('ab') gives Counter({'a': 1}). most_common() returns elements in descending frequency.
counter count elements frequency most common tally