A quick guide to Python's Dictionary

A quick guide to Python's Dictionary

posted Originally published at dev.to 3 min read

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}

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])

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])

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)

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)
  • 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")


**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

1 Comment

0 votes

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

I Wrote a Script to Fix Audible's Unreadable PDF Filenames

snapsynapseverified - Apr 20

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!