Python Dictionaries

Introduction

Somebody hit lists with gamma rays. Okay, so Dictionaries aren’t the Incredible Hulk, but they are supercharged in what they can do. In other languages, dictionaries are referred to as hashes, associative arrays, and associative lists. It’s probably best to think of them as associative lists because that’s exactly what they are. Dictionaries are lists that associate two values with one another. To think of it in terms of an actual dictionary, they associate a word, or key with a definition, or value. They function sort of like a list with custom indexes.



Dictionaries allow you to associate information in a way that no other data structure will. They allow you store and retrieve related information in a way that means something both to humans and computers.

Creating Dictionaries

Creating dictionaries is very similar to creating lists. One main difference is that dictionaries use curly brackets {} instead of square ones.

Empty

Like lists, dictionaries can be created with nothing in them. This makes sense because values can be populated from an external source any time. Dictionaries are great for this, especially when it comes to databases.

new_dictionary = {}

With Entries

Dictionaries can also be created with as many or as few entries as you’d like. Since dictionaries can be expanded or shrunk at any time, it doesn’t matter exactly how much data you start with, but if you know exactly what you need to start, you can absolutely set the dictionary up that way.

distro_install_command = {'Debian': 'apt-get', 'Ubuntu': 'apt-get', 'Fedora': 'dnf', 'CentOS': 'yum', 'OpenSUSE': 'zypper', 'Arch': 'pacman', 'Gentoo': 'emerge'}

As you can see, the dictionary values are wrapped in curly brackets. Inside, each key is separated from its accompanying value with a colon, and each set is separated by a comma. It’s sort of difficult to see the way it is presented above. Often times, dictionaries use spaces and line breaks to organize entries.

distro_install_command = {'Debian': 'apt-get', 
						'Ubuntu': 'apt-get',
						'Fedora': 'dnf', 
						'CentOS': 'yum',
						'OpenSUSE': 'zypper',
						'Arch': 'pacman',
						'Gentoo': 'emerge'
}

Organizing the dictionary the way it is above is much more readable. While it may seem like formatting it this way violates Python’s strict spacing rules, in reality, it doesn’t because the dictionary has it’s own structure delineated by the brackets and commas.

Navigating Dictionaries

Navigating dictionaries is a lot like navigating lists. Instead of specifying an index, you must specify a key to access a value.

distro_install_command = {'Debian': 'apt-get', 
                        'Ubuntu': 'apt-get',
                        'Fedora': 'dnf', 
                        'CentOS': 'yum',
                        'OpenSUSE': 'zypper',
                        'Arch': 'pacman',
                        'Gentoo': 'emerge'
}

print(distro_install_command['Gentoo'])

Navigating using numeric indexes will not work with dictionaries. You must use keys. Therefore, it is also important to know what keys are being used in order to successfully navigate through dictionaries.

Adding and Removing

Adding and removing entries from dictionaries is very simple. Keep in mind that dictionaries are not necessarily ordered, so it doesn’t really matter what position entries are added at.

Adding Items

Adding entries to a dictionary is more like defining a new variable than adding a new element to a list. To do so, you must first specify the name of the dictionary that the entry is being added to, then the key. Then, you can set that key equal to its value.

distro_install_command = {}
distro_install_command['Debian'] = 'apt-get'

Even though only stings have been used so far, both strings and numbers can be used as keys, and values can be nearly any type. Take a look at the example below.

test_dict = {}
test_dict[3] = "Boat"
test_dict['Green'] = 42
test_dict['a list'] = [2, 4, 6, 8, 10]
other_dict = {'a': 1, 'b': 2, 'c': 3}
test_dict['a dict'] = other_dict
print(test_dict)
print(test_dict['a dict'])
print(test_dict['a list'][1])

As you can see, dictionaries are incredibly flexible in what they can store and how they can be used. The lack of restrictions placed on values allows nearly any data type and structure to be associated with a number or string to be stored and retrieved.

Removing Items

The easiest way to remove entries from a dictionary is to use the del operator. The del operator actually works on lists too, but there are other methods for that, so it hasn’t been covered until now. del will just delete the specified entry.

distro_install_command = {'Debian': 'apt-get',
                        'Ubuntu': 'apt-get',
                        'Fedora': 'dnf',
                        'CentOS': 'yum',
                        'OpenSUSE': 'zypper',
                        'Arch': 'pacman',
                        'Gentoo': 'emerge'
}
del distro_install_command['Ubuntu']
print(distro_install_command)

Conclusion

Dictionaries are yet another useful and dynamic weapon in Python’s arsenal. They are an excellent data storage structure and can be used for a lot more. Practice accessing, adding, and removing entries from dictionaries, and try to get a feel for how they operate. The next guide will delve deeper into dictionaries and explore how to use methods with them and iterate over them with the for loop.

Table of Contents

  1. Python Introduction and Installation Guide
  2. Python Files and the Interpreter
  3. Experimenting With Numbers and Text In Python
  4. Python Variables
  5. Working With Number Variables In Python
  6. Python String Basics
  7. Advanced Python Strings
  8. Python Comments
  9. Python Lists
  10. Python List Methods
  11. Python Multidimensional Lists
  12. Python Tuples
  13. Python Boolean Operators
  14. Python If Statements
  15. Python While Loops
  16. Python For Loops
  17. Python Dictionaries
  18. Python Advanced Dictionaries
  19. Python Functions


Comments and Discussions
Linux Forum