Clicky

Basic Python Programming Code Snippets: Dictionaries


Basic Python Programming Code Snippets:

Dictionary Data Structure

March 23, 2023

Basic Python

Dictionaries are one of the data structures made available in Python. Like other Python data structures, they allow you to store and manipulate collections of items. Along with Lists, they are one of the more commonly used Python data structures. They can be used for a wide variety of applications, from simple data storage to complex algorithmic operations. In this article, we will explore the basics of working with dictionaries - how to create and manipulate dictionaries, access individual values, and perform operations on entire dictionaries. Knowing how to work with dictionaries will expand your programming options as a Python developer. Below are some very basic syntax for creating and manipulating Dictionaries. You can also watch the Python Playlist for demonstrations. It covers both Lists and Dictionaries.

Dictionaries store data values in key:value pairs. Like Lists, a dictionary is a collection which is alterable. However, unlike Lists, Dictionaries do not allow for duplicates and as of Python 3.7 they are ordered collections.

  • No Duplicates: Dictionaries require unique keys for key-value pairs.
  • Ordered vs Unordered
    • Ordered Collections: As of Python 3.7, dictionaries are ordered. Now when iterating over a dictionary, the key-values are guaranteed to be returned in the same order each time. Order is forced within the structure.
    • Unordered Collections: Prior to Python 3.7, the built-in dictionary type was unordered. Order could only be achieved by using the subclass OrderedDict. Otherwise, when iterating over a dictionary, you would not be guaranteed to have key-values returned in any particular order. There was no mechanism that forced order on the structure. Any order returned had nothing to do with the way the structure was designed.

Create a Dictionary

Dictionaries hold data in the form of key-value. Keys are unique identifiers with values associated to them. Any single key-value entry can be called using the key name. The collection is enclosed by curly brackets.

The syntax for creating a dictionary is provided below. Note that the syntax is similar to that of Python set creation except that dictionaries use key-value pairs. Both structures use curly braces for structure creation.

variable = {key1:value1, key2:value2, key3:value3}

Our example uses archived unemployment rates by U.S. State.

myDictionary = { 'Florida': 4.9,
'Illinois': 4.6,
'Pennsylvania': 6.4,
'Ohio': 4.9,
'Georgia': 5.4,
'North Carolina':  5.5,
'Michigan':  4.8,
'Virginia':  4.1,
'Washington':  4.6,
'Massachusetts': 5.8,
'Arizona':  5.5,
'Indiana': 4.7,
'Tennessee': 4.9,
'Missouri': 4.2,
'Maryland': 4.7,
'Wisconsin': 4.6,
'Minnesota': 3.7,
'Colorado': 3.0 ,
 'Alabama': 6.2,
 'South Carolina': 5.5,
 'Louisiana': 5.9,
'Kentucky': 5.8,
'Oregon': 4.8,
 'Oklahoma': 4.2,
 'Connecticut': 5.5,
 'Iowa': 3.7,
 'Arkansas': 4.2,
'Mississippi': 6.5,
 'Utah': 3.4,
 'Kansas': 4.0,
'Nevada': 5.9,
'New Mexico': 6.4,
'Nebraska': 3.0,
'West Virginia': 6.5,
 'Idaho': 3.9,
 'Hawaii': 3.1,
 'Maine': 3.6,
 'New Hampshire': 2.7,
'Rhode Island': 4.6,
 'Montana': 4.6,
'Delaware': 4.6,
 'South Dakota': 2.7,
 'North Dakota': 2.9,
'Alaska': 6.6,
'Vermont': 3.4,
'Wyoming': 5.0,
'New Jersey': 4.3,
'New York': 4.8,
'California': 5.5,
'Texas': 4.4}


Print Command: Printed Dictionary

Now you can print the entire dictionary object using the print function.

print(myDictionary)

You can also print a single value using the key name. In this example, the key name 'New York' is included in brackets to obtain the value 4.8.

print(myDictionary['New York'])

Returns all keys

print(myDictionary.keys())

Returns all values

print(myDictionary.values())

Applying the Sorted Function to a Dictionary

Returns both keys and values sorted

print(sorted(myDictionary.items()))

Returns keys sorted

print(sorted(myDictionary.keys()))

Returns values sorted

print(sorted(myDictionary.values()))

Update, Add, Clear, and Delete Key-Values of a Dictionary

Update: You can make changes to existing keys. In this example, the unemployment rate of New York will e changed from 4.8 to 1.5.

myDictionary['New York'] = 1.5; # update existing entry

Add: Add a new key-value to the dictionary using the syntax below.

myDictionary['Dummy State'] = 0.1; # Add new entry

Delete: Entries can be deleted using the syntax below.

del myDictionary['Dummy State'];

Other Deletion Options

For more impactful deletion actions, clear() and del can be used.


Clear(): You can remove all entries in dictionary while maintaining the dictionary structure.

myDictionary.clear();

del: You can also delete the entire dictionary structure.

del myDictionary;

Loop in Dictionary Using the keys() and values()

The process of iterating over a dictionary means going through each item in the dictionary one by one and performing some operation on it. Like most programming languages, a for loop can be used to iterate over a dictionary.

Returns keys only

for x in myDictionary.keys():
    print('key: ' + str(x) )

Returns both keys and values

for x , y in myDictionary.items():
    print('key: ' + str(x) + '   '+ 'value: '+ str(y))



Watch the YouTube Python Playlist



Visit the YouTube Channel and Watch the Python Playlist on Dictionaries and Lists.


Conclusion

Dictionaries are a fundamental and versatile data structure in Python that allow for efficient storage and retrieval of key-value pairs. With its powerful built-in methods and operations, dictionaries can be used to solve a wide variety of problems in data science, web development, and other fields. Understanding the inner workings of dictionaries, as well as their strengths and limitations, is crucial for any programmer seeking to write efficient and scalable code in Python. Whether you are a beginner or an experienced developer, mastering dictionaries is an essential skill that will greatly enhance your Python programming abilities.

For more articles on Python data structures, see the following:


For a more advanced review of Python Data Structures, see the following resources:



Learn to Code with Educative.io

Visit Educative.io

Educative

Tutorials Point Offers Python Programming Courses

Polish Your Python Skills. Visit Tutorials Point!

Tutorials Point


Integrate Data Science into Your Learning Experience with DataCamp

Visit DataCamp Today!