Dictionaries and Sets in Python

Dictionaries are a data structure in Python that store information in key-value pairs. The keys are unique identifiers that map to their respective values. Duplicate keys are not allowed.

Dictionaries are recognized by curly brackets and colons that separate the keys and values. Retrieving values is as simple as referencing the key name within square brackets or by passing the key name into the get() method.

user = {
	"name": "Peter Gibbons",
	"profession": "Software Engineer",
	"age": 28
}

print(user['name'])
print(user.get('profession'))

Values can be changed by assigning a new value to the key. A new key and a new value are created if the key does not already exist.

user = {
	"name": "Peter Gibbons",
	"profession": "Software Engineer",
	"age": 28
}
user["age"] += 1
user["burned out"] = True

Keys must be a value with an immutable type. For example, lists cannot be used as keys but strings, numbers, and tuples can.

Removing Items

You can delete key-value pairs with the del keyword. Delete the dictionary from memory with the del keyword as well.

user = {
	"name": "Peter Gibbons",
	"profession": "Software Engineer",
	"age": 28
}

del user["age"]
print(user)

del user
print(user)    # produces a NameError

Dictionaries have methods for removing elements. The pop() method removes and returns the value referenced by the key. The popitem() method removes and returns the last key-value in the dictionary as a tuple.

Remove all the dictionary values with the clear() method.

colors = {
	"red": 1,
	"white": 5,
	"blue": 2,
	"green": 9,
	"purple": 3
}

red_value = colors.pop('red')
last = colors.popitem()
print('Red value:', red_value)  # prints red
print('Last:', last)			# prints ('purple', 3)

colors.clear()
print(colors)					# prints {}

Iterating Dictionaries

Dictionaries have methods for returning their keys and values as an iterable object.

Method Description
keys() Returns a list of keys in the dictionary
values() Returns a list of values in the dictionary
items() Returns a list of tuples containing both the keys and values
user = {
	"name": "Peter Gibbons",
	"profession": "Software Engineer",
	"age": 28
}
print(user.keys())

for key in user.keys():
	print(key)
	
for value in user.values():
	print(value)
	
for key, value in user.items():
	print(key, ":", value)

Check If Key Exists

Python produces a KeyError if you try to access a key that does not exist. Check if a key exists before trying to access it.

user = {
	"name": "Peter Gibbons",
	"profession": "Software Engineer",
	"age": 28
}

if "height" in user:
	print(user["height"])
else:
	print('The user dictionary does not contain a "height" key')

Sets

Sets are a data structure in Python that resemble a list but with a few big differences. They look like lists but use curly brackets instead of square brackets when they are defined.

my_set = {'one', 'two', 'three'}

Sets can be created using the set() function and passing in an iterable object such as a list.

my_set = set([1,2,3,4,5])

Sets are a collection of distinct objects and do not allow duplicate values. Redundant values are removed during the creation of the set.

my_set = {'one', 'two', 'one', 'three'}
print(my_set)  # prints {'one', 'two', 'three'}

Add an Element to a Set

You can add new elements to a set using the add() method. New elements must be distinct.

my_set = {'one', 'two', 'one', 'three'}
my_set.add('four')
my_set.add('one')
print(my_set)  # prints {'one', 'two', 'three', 'four'}

Remove an Element From a Set

Elements in a set can be deleted using the remove() method. A KeyError occurs if the item is not in the set.

my_set = {'one', 'two', 'one', 'three'}
my_set.remove('one')  # removes 'one'
my_set.remove('four')  # returns a KeyError

Sets also include a discard() method that removes elements and does nothing if the element is not found.

my_set = {'one', 'two', 'one', 'three'}
my_set.discard('one')  # removes 'one'
my_set.discard('four')  # does nothing

Pop and Clear

Sets are unordered. You cannot use slicing or indexing to retrieve values. The pop() method returns a value and removes it from the set. However, because sets are unordered you may get a different element each time the script runs.

my_set = {'one', 'two', 'one', 'three'}
value = my_set.pop()
print(value)  # may print 'one' or 'two' or 'three'

Remove all the elements from a list by using the clear() method.

my_set = {'one', 'two', 'one', 'three'}
my_set.clear()
print(my_set)  # prints an empty set()