Dictionaries in Python

dictionaries in python

A dictionary in python is a collection of unordered data. By unordered, we mean it is not in any particular order.

To contrast this concept, lists and arrays in Python contain ordered data with an index. The value of the first item in the list is always that value unless it is changed.

The most important feature of a dictionary is the key:value relationship of its data. For every value, there must be a key.

Creating a New Dictionary

To create a new, empty dictionary, you simply use empty curly brackets or the dict function.

Example:

new = {}

new = dict()

But what if you wanted to create a dictionary that already contained data? Simply enter the key:value date inside the curly brackets.

Example:

ALEAST = { ‘Boston’:’Red Sox’, ‘Toronto’:’Blue Jays’, ‘Tampa’:’Rays’, ‘Baltimore’:’Orioles’, ‘New York’:’Yankees’}

Here’s how to create a dictionary containing data using the dict function. If you use this method, then each key:value pair is entered as a list.

ALCENTRAL = { [[‘Chicago’:’White Sox’], [‘Cleveland’:’Indians’], [‘Kansas City’:’Royals’], [‘Detroit’:’Tigers’, ‘Minnesota’:’Twins’] }

Adding Data to a Dictionary

This is how to add a new key:value pair to an existing dictionary.

ALWEST = { ‘Anaheim’:’Angels’, ‘Seattle’:’Mariners’, ‘Texas’:’Rangers’, ‘Houston’:’Astros’ }

ALWEST[‘Oakland’] = ‘Athletics’

print(ALWEST)

{ ‘Anaheim’:’Angels’, ‘Seattle’:’Mariners’, ‘Texas’:’Rangers’, ‘Houston’:’Astros’, ‘Oakland’:’Athletics’ }

Here’s what to type if you want to see a certain value in a dictionary:

ALEAST[‘Baltimore’]

‘Orioles’

Deleting an Item from a Dictionary

The following code shows how to delete data from a dictionary.

The Houston Astros left the National League to join the American League in 2012. Let’s express this in Python.

NLCENTRAL = {‘Chicago’:’Cubs’, ‘St Louis’:’Cardinals’, ‘Pittsburgh’:’Pirates’, ‘Cincinnati’:’Reds’, ‘Milwaukee’:’Brewers’, ‘Houston’:’Astros’}

del(NLCENTRAL[‘Houston’])

print(NLCENTRAL)

{‘Chicago’:’Cubs’, ‘St Louis’:’Cardinals’, ‘Pittsburgh’:’Pirates’, ‘Cincinnati’:’Reds’, ‘Milwaukee’:’Brewers’}

This will remove both the key and its associated value.

Leave a comment

Your email address will not be published. Required fields are marked *