Dictionary in Python

A dictionary is an example of a key-value store also known as Mapping in Python. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. As they are primarily used for referencing items by key, they are not sorted.

Creating a Dictionary

Dictionaries can be initiated in many ways:

d = {} # empty dict d = {'key': 'value'} # dict with initial values d = dict() # empty dict d = dict(key='value') # explicit keyword arguments d = dict([('key', 'value')])

Rules for creating a dictionary:

  • Every key must be unique (otherwise it will be overridden)
  • Every key must be hashable (can use the hash function to hash it; otherwise TypeError will be thrown)
  • There is no particular order for the keys.
# Creating and populating it with values stock = {'eggs': 5, 'milk': 2} # Or creating an empty dictionary dictionary = {} # And populating it after dictionary['eggs'] = 5 dictionary['milk'] = 2 # Values can also be lists mydict = {'a': [1, 2, 3], 'b': ['one', 'two', 'three']} # Use list.append() method to add new elements to the values list mydict['a'].append(4) mydict['b'].append('four') # We can also create a dictionary using a list of two-items tuples iterable = [('eggs', 5), ('milk', 2)] dictionary = dict(iterables) # Or using keyword argument: dictionary = dict(eggs=5, milk=2)

Accessing values of a dictionary

dictionary = {"Hello": 1234, "World": 5678} print(dictionary["Hello"])

1234

The string “Hello” in this example is called a key. It is used to lookup a value in the dict by placing the key in square brackets.

The number 1234 is seen after the respective colon in the dict definition. This is called the value that “Hello” maps to in this dict.

Also, Read Loops in Python.

Looking up value like this with a key that does not exist will raise a KeyError exception, halting execution if uncaught. If we want to access a value without risking a KeyError, we can use the dictionary.get method. By default, if the key does not exist, the method will return None. We can pass it a second value to return instead of None in the event of a failed lookup.

w = dictionary.get("whatever") x = dictionary.get("whatever", "nuh-uh")

In this example w will get the value None and x will get the value “nuh-uh”.

Iterating Over a Dictionary

If you use a dictionary as an iterator (e.g. in a for statement), it traverses the keys of the dictionary. For example:

d = {'a': 1, 'b': 2, 'c':3} for key in d: print(key, d[key])

a 1
b 2
c 3

The items() method can be used to loop over both the key and value simultaneously:

for key, value in d.items(): print(key, value)

a 1
b 2
c 3

While the values() method can be used to iterate over only the values, as would be expected:

for key, value in d.values(): print(key, value)

3
2
1

Dictionaries Example

Dictionaries map keys to values:

car = {} car["wheels"] = 4 car["color"] = "Red" car["model"] = "Corvette"

Dictionary values can be accessed by their keys:

print("Little " + car["color"] + " " + car["model"])

Little Red Corvette

Dictionaries can also be created in a JSON style:

car = {"wheels": 4, "color": "Red", "model": "Corvette"}

Dictionary values can be iterated over:

for key in car: print(key,":",car[key])

wheels : 4
color : Red
model : Corvette

I hope you liked this article on Dictionaries in Python, feel free to ask your valuable questions in the comments section below. You can follow me on Medium to learn machine learning for free.

Follow Us:

Leave a Reply