26
Every Python Dictionary Method Explained Simply
Here is a quick recap of how dictionaries work.
- written with
{}
- changeable, unordered, indexed
- comes with key-pair values & no duplicates
- looks something like this:
pythondictionary = {1: 'python', 2: 'data science', 'third': 'JavaScript'}
Here is every Python Dictionary method available.
To combine two dictionaries, use a leading **
and then add them to a dictionary. Here is an example:
a = {'a':1}
b = {'b':2}
c = {**a, **b}
print(c)
# this will return:
# {'a': 1, 'b': 2}
To remove all items inside a Python dictionary, use clear()
pythondictionary = { "a":1, "b":2, "c":3 }
print(pythondictionary.clear())
# this will return:
# None
copy()
will create a shallow copy of the original dictionary.
pythondictionary = { "a":1, "b":2, "c":3 }
c = pythondictionary.copy()
print(c)
# this will return:
# { "a":1, "b":2, "c":3 }
fromkeys()
lets you create a dictionary from a set of keys stored in a list or tuple. For example:
keys = ("a", "b", "c")
value = [1, 2, 3]
d = dict.fromkeys(keys, value)
print(d)
# this will return:
# {'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
You can access dictionary attributes with []
like this:
d = { "a":1, "b":2, "c":3 }
print(d["a"])
# this will return:
# 1
However, the safest way to access attributes in a Python dictionary is through using the get()
function. This makes the action explicit. If the attribute doesn’t exist, it will return None
. If you used []
instead of get()
and the value doesn’t exist, you will get a KeyError
instead.
d = { "a":1, "b":2, "c":3 }
print(d.get("a"))
# this will return:
# 1
If you want to get an attribute but not sure if it exists or not, you can also assign your own error value to something like undefined
with get()
. Here is an example:
d = { "a":1, "b":2, "c":3 }
print(d.get("f", "undefined))
# this will return:
# undefined
item()
will return a dictionary’s key and value pairs as a list of tuples. Here is an example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
result = car.items()
print(result)
# this will return:
# dict_items([('make', 'Mitsubishi'), ('model', 'Lancer'), ('year', 2007), ('color', 'silver')])
Now you can iterate over the results with a loop like this:
for item in result:
print(item)
# this will return:
# ('make', 'Mitsubishi')
# ('model', 'Lancer')
# ('year', 2007)
# ('color', 'silver')
Use keys()
if you only need the keys inside a dictionary. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
for key in car.keys():
print(key)
# this will return:
# make
# model
# year
# color
To only access the values inside a dictionary, use values()
. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
for value in car.values():
print(value)
# this will return:
# Mitsubishi
# Lancer
# 2007
# silver
If you want to remove a specific item from a dictionary based on key name, you can use pop()
. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
car.pop("year")
print(car)
# this will return:
# {'make': 'Mitsubishi', 'model': 'Lancer', 'color': 'silver'}
To remove the last item in the dictionary, use popitem()
. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
car.popitem()
# this will return:
# ('color', 'silver')
print(car)
# this will return:
# {'make': 'Mitsubishi', 'model': 'Lancer', 'year': 2007}
If a key doesn’t exist, it returns None
by default. However, you can set the return value through setdefault()
. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
print(car.setdefault("origin", "undefined"))
print(car.setdefault("model", "undefined"))
# this will return:
# undefined
# followed by (because the key exists):
# Lancer
To insert an item into a dictionary, use update()
. For example:
car = {
"make":"Mitsubishi",
"model":"Lancer",
"year":2007,
"color":"silver"
}
car.update({"origin":"Japan"})
print(car)
# this will return:
# {'make': 'Mitsubishi', 'model': 'Lancer', 'year': 2007, 'origin': 'Japan'}
And that's basically it.
26