Using Python dict() to Create and Manipulate Dictionaries
This article explains how the Python dict() function creates new dictionaries, demonstrates various ways to supply key/value pairs—including empty dictionaries, literal mappings, keyword arguments, lists of tuples, and zip()—and provides examples of common dictionary methods such as clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, and update.
The dict() function in Python creates a new dictionary and works similarly to the dict.update() method.
Syntax: dict(key/value) where key/value represents one or more key‑value pairs used to build the dictionary.
Examples:
# !/usr/bin/python3
# Create an empty dictionary
dict0 = dict()
print('dict0:', dict0)
# Create a dictionary with literal key/value pairs
dict1 = dict({ 'three': 3, 'four': 4 })
print('dict1:', dict1)
# Create a dictionary using keyword arguments
dict2 = dict(five=5, six=6)
print('dict2:', dict2)
# Create a dictionary from a list of tuples
dict3 = dict([('seven', 7), ('eight', 8)])
print('dict3:', dict3)
# Create a dictionary using zip()
dict5 = dict(zip(['eleven', 'twelve'], [11, 12]))
print('dict5:', dict5)
Output of the above examples:
dict0: {}
dict1: {'four': 4, 'three': 3}
dict2: {'five': 5, 'six': 6}
dict3: {'seven': 7, 'eight': 8}
dict5: {'twelve': 12, 'eleven': 11}
Common dictionary methods:
# clear() – empties the dictionary
stu = {'num1': 'Tom', 'num2': 'Lucy', 'num3': 'Sam'}
print(stu.clear()) # prints None
# copy() – returns a shallow copy
stu2 = stu.copy()
print('stu2:', stu2)
# fromkeys() – creates a new dict from a sequence of keys
names = ['tom', 'lucy', 'sam']
print(dict.fromkeys(names))
print(dict.fromkeys(names, 25)) # default value 25
# get() – retrieve value for a key
print(stu.get('num2')) # Lucy
# items() – returns a view of (key, value) pairs
print(stu.items())
# keys() – returns a view of keys
print(stu.keys())
# pop() – remove a key and return its value
name = stu.pop('num2')
print(name, stu)
# popitem() – remove and return an arbitrary (key, value) pair
pair = stu.popitem()
print(pair, stu)
# setdefault() – get value if key exists, otherwise insert key with default None
value = stu.setdefault('num5')
print(value, stu)
# update() – add or modify key‑value pairs
stu.update({'num4': 'Ben'})
print(stu)
These examples illustrate how to create dictionaries in various ways and manipulate them using built‑in methods.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.