DEV Community

Cover image for A quick guide to Python's Dictionary
Ajibola jr.
Ajibola jr.

Posted on

A quick guide to Python's Dictionary

A dictionary is one of the most significant data structures in Python; it is literally a dictionary, mutable, not a sequence type, but it can be adapted for sequence processing.

How do we make a dictionary?


empty_dictionary = {}
dictionary = {"man": "woman", "boy": "girl", "tall": "short", "giant": "dwarf"}
staff_address = {"Jibbs": "London", "KB": "Milton Keynes", "MJ": "Stoke-on-Trent"}
phone_numbers = {"Jibbs": 473747383, "KB": 483943929, 'MJ': 39394930}
staff_id = {34: "JB", 23: "KB", 21: "MJ"}
indexes = {23: 43, 43: 75, 38: 87}

Enter fullscreen mode Exit fullscreen mode

Using the above examples:

  • The first one is an empty dictionary, constructed with an empty pair of curly braces.
  • The second and third ones use keys and values that are both strings.
  • In the fourth one, the keys are strings while the values are integers.
  • In the fifth example, the key is an integer while the values are strings.
  • In the last example, both keys and values are integers.

I used the last two examples to establish that reverse layout (key -> numbers, values -> strings), as well as number -> number combinations, are possible.

A dictionary is not a list (I'll cover lists in a separate article), it's a set of key-value pairs, and the following applies:

  • The key can be any immutable data type, e.g., integer, float, or even a string. never a list.
  • Each key must be unique, as it's not possible to have more than one key of the same value.
  • Functions like len() work for dictionaries too; it returns the number of key-value elements in the dictionary.

Now, it's time to work with our examples.

  • Let's print the second dictionary as a whole using the print() function: print(dictionary)

output: {'man': 'woman', 'boy': 'girl', 'tall': 'short', 'giant': 'dwarf'}

  • Getting a single element from the dictionary: print(dictionary['giant']) output => dwarf

print(dictionary['long'])
output => KeyError: 'long'

What just happened? We tried to get a nonexistent key from the dictionary, but an exception was thrown; it's nothing to worry about. Here's a workaround to fix the error.

print(dictionary.get('long'))
output => None

This means a dictionary['key'] will raise an error if the key is missing, while dictionary.get('key') will return None.

  • Looping through a dictionary
for elem in dictionary:
    print(elem, '=>', dictionary[elem])
Enter fullscreen mode Exit fullscreen mode

output: man => woman
boy => girl
tall => short
giant => dwarf

  • Print the dictionary length using len()
    print(len(dictionary))
    output: 4

  • Browse a dictionary using the keys() method

for key in dictionary.keys():
    print(key, '=>', dictionary[key])
Enter fullscreen mode Exit fullscreen mode

output: man => woman
boy => girl
tall => short
giant => dwarf

  • Browse the dictionary using the items() method This method returns a tuple where each tuple is a key-value pair
for word, opposite in dictionary.items():
    print(key, '=>', opposite)
Enter fullscreen mode Exit fullscreen mode

output: man => woman
boy => girl
tall => short
giant => dwarf

  • Can you print only the keys or the values? Of course, here's the solution:
#To get only the keys 
for key in dictionary.keys():
    print(key)

#To get only the values
for value in dictionary.values():
    print(value)
Enter fullscreen mode Exit fullscreen mode
  • Modifying dictionaries
dictionary['man'] = "New Man"
print(dictionary)
Output: {'man': 'New Man', 'boy': 'girl', 'tall': 'short', 'giant': 'dwarf'}

#Adding new keys to the dictionary
dictionary['far'] = "near"
print(dictionary)
Output: {'man': 'New Man', 'boy': 'girl', 'tall': 'short', 'giant': 'dwarf', 'far': 'near'}

#Adding new keys using the _update()_ method

dictionary.update({'dim': 'dull'})
print(dictionary)
Output: {'man': 'New Man', 'boy': 'girl', 'tall': 'short', 'giant': 'dwarf', 'far': 'near', 'dim': 'dull'}

#Removing a key
del dictionary['tall']
print(dictionary)
Output: {'man': 'New Man', 'boy': 'girl', 'giant': 'dwarf', 'far': 'near', 'dim': 'dull'}

#Using the _popitem()_ method
dictionary.popitem() #Please note, if you use this method on Python version < 3.6, it'll remove a random element from the dictionary
print(dictionary)
Output: {'man': 'New Man', 'boy': 'girl', 'giant': 'dwarf', 'far': 'near'}

#Check if an element exists using the _in_ keyword
if "man" in dictionary:
   print("yes")
else:
   print("no")
Output: yes

#Check if an element doesn't exists using the _not in_ keyword
if "close" not in dictionary:
   print("yes")
else:
   print("no")

Enter fullscreen mode Exit fullscreen mode

Key Takeaway

  • A dictionary is a mutable data type.
  • It's literally a dictionary.
  • It can be created using a pair of curly braces {}
  • You can check the existence of a Python dictionary using the in() or not in keyword.
  • You can use a for loop to loop through a dictionary.
  • You can copy its content using the copy() method.
  • You can remove an element from a dictionary using the del keyword.
  • You can loop through a dictionary's keys and values using the items() keyword

Top comments (1)

Collapse
 
harsh2644 profile image
Harsh

Nice quick guide! ๐Ÿ”ฅ Dictionaries in Python are truly underrated powerhouses.

One thing I'd add for beginners: dictionary lookups are O(1) time complexity โ€” meaning they're SUPER fast even with massive datasets. That's why they're used everywhere in real-world applications like caching, JSON parsing, and configuration management.

Also, fun fact: From Python 3.7+, dictionaries preserve insertion order! So if order matters, you don't always need OrderedDict anymore.

Great examples with staff_address and phone_numbers โ€” relatable use cases! ๐Ÿ™Œ