Dictionary initialization

Lists and collections / Dictionaries

# Empty dictionary
d1 = {}
d2 = dict()

# init with some data
d3 = {1: "one", 2: "two"}
d4 = dict(one=1, two=2)
# d4 is {'one': 1, 'two': 2}

# A new dictionary: d4 stays as it was
d5 = dict(d4, three=3)
# d5 is {'one': 1, 'two': 2, 'three': 3}

# From pairs
d6 = dict([(1, "one"), (2, "two")])
# d6 is {1: 'one', 2: 'two'}

# From two sequences: zip pairs them up
numbers = [1, 2, 3]
names = ["one", "two", "three"]
d7 = dict(zip(numbers, names))
# d7 is {1: 'one', 2: 'two', 3: 'three'}

print(f'{d1 = }')
print(f'{d2 = }')
print(f'{d3 = }')
print(f'{d4 = }')
print(f'{d5 = }')
print(f'{d6 = }')
print(f'{d7 = }')