DEV Community

loading...
Cover image for Every Python Dictionary Method Explained Simply

Every Python Dictionary Method Explained Simply

Aphinya Dechalert
Python, Angular, React, and Code Things ☕🍕☕🍕☕🍕 Follow me at twitter.com/dottedsquirrel
Originally published at dottedsquirrel.com ・3 min read

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'}
Enter fullscreen mode Exit fullscreen mode

Here is every Python Dictionary method available.

Combining dictionaries

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}
Enter fullscreen mode Exit fullscreen mode

dict.clear()

To remove all items inside a Python dictionary, use clear()

pythondictionary = { "a":1, "b":2, "c":3 }
print(pythondictionary.clear())

# this will return:
# None
Enter fullscreen mode Exit fullscreen mode

dict.copy()

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 }
Enter fullscreen mode Exit fullscreen mode

dict.fromkeys()

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]}
Enter fullscreen mode Exit fullscreen mode

dict.get()

You can access dictionary attributes with [] like this:

d = { "a":1, "b":2, "c":3 }
print(d["a"])

# this will return:
# 1
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

dict.items()

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')])
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

dict.keys()

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
Enter fullscreen mode Exit fullscreen mode

dict.values()

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
Enter fullscreen mode Exit fullscreen mode

dict.pop()

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'}
Enter fullscreen mode Exit fullscreen mode

dict.popitem()

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}
Enter fullscreen mode Exit fullscreen mode

dict.setdefault()

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
Enter fullscreen mode Exit fullscreen mode

dict.update()

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'}
Enter fullscreen mode Exit fullscreen mode

And that's basically it.

Discussion (0)