Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dict.fromkeys

Creates a dictionary whose supplied keys initially refer to a common value.

Version: Python 3.14; repository image, production runtime not attested

Syntax

dict.fromkeys(iterable, value=None, /)

Creates a dictionary whose supplied keys initially refer to a common value.

A mutable initial value is shared; a comprehension can create a distinct list per key instead.

Creates one binding per key with the same initial object, defaulting to None. The list supplied once for x and y is shared, so appending via x also appears at y. A comprehension that creates a fresh list for each key avoids this sharing.

m = dict.fromkeys("ab", [])
assert m["a"] is m["b"] and dict.fromkeys("a") == {"a": None}

Examples

m = dict.fromkeys(("x", "y"), [])
m["x"].append(8)
print(m)

Result

{'x': [8], 'y': [8]}

Creates one binding per key with the same initial object, defaulting to None. The list supplied once for x and y is shared, so appending via x also appears at y. A comprehension that creates a fresh list for each key avoids this sharing.

Sources