Python Dictionaries: Key-Value Pair Mapping

Understanding the Basics of Creating, Accessing, and Modifying Python Dictionaries

Python dictionaries provide a powerful way to store and organize data as key-value pairs, which is known as mapping. Unlike sequences that store objects by their relative position, mappings use a unique key to store objects. This key-based approach makes Python dictionaries incredibly versatile and suitable for representing a wide range of real-world scenarios. It’s important to note that since mappings are not defined by order, Python dictionaries won’t retain the order of objects. In this article, we’ll delve into the basics of Python dictionaries, including how to construct a dictionary, access objects within it, create nested dictionaries, and use some of the basic dictionary methods.

Constructing a Dictionary

In Python, you can construct a dictionary using a set of key-value pairs enclosed in curly braces {}. Each key-value pair is separated by a colon, and the pairs are separated by commas. Here’s an example of a simple dictionary

fruit = {'apple': 2, 'banana': 3, 'orange': 5}

In this example, the keys are strings (‘apple’, ‘banana’, ‘orange’) and the values are integers (2, 3, 5). You can access the values in the dictionary by using the keys as indices. For example, fruit[‘apple’] would return the value 2.

fruit['apple']
2

Its important to note that dictionaries are very flexible in the data types they can hold. For example:

fruit = {'name': 'apple','color': 'red','vitamins': ['A', 'C']}

here Vitamin contains the list and to access the value associated with a particular key in a dictionary, you can use square bracket notation with the key inside the brackets. For example, to access the value associated with the ‘vitamins’ key in the ‘fruit’ dictionary, you can use the following code: fruit[‘vitamins’]

fruit['vitamins']
['A', 'C']

This will return the value associated with the ‘vitamins’ key, which in this case is the list [‘A’, ‘C’].Once you have the list, you can perform various operations on it. For example, you can access individual elements in the list using their index, like this: fruit[‘vitamins’][0]. This would return the string ‘A’, which is the first item in the list.

fruit['vitamins'][0]
'A'

you can also call methods on that value, for example


fruit['vitamins'][0].lower()
'a'

This would return the string ‘a’, since the lower() method converts the string ‘A’ to lowercase.

you can modifiy the element of the dictionary. for example


fruit['vitamins'].append('B')

fruit
{'name': 'apple', 'color': 'red', 'vitamins': ['A', 'C', 'B']}

here, new element ‘B’ to the vitamins has been added.

We can also create keys by assignment. For instance if we started off with an empty dictionary, we could continually add to it:

Create a new dictionary
d = {}
Create a new key through assignment
d['animal'] = 'Dog'
Can do this with any object
d['answer'] = 42
d
{'animal': 'Dog', 'answer': 42}

Nesting with Dictionaries

By now, you might be realizing how flexible and powerful Python is, especially when it comes to nesting objects and calling methods on them. To further illustrate this, consider the following example of a dictionary nested inside another dictionary

 Dictionary nested inside a dictionary nested inside a dictionary
d = {'key1':{'nestkey':{'subnestkey':'value'}}}

Wow! That’s a quite the inception of dictionaries! Let’s see how we can grab that value:

Keep calling the keys
d['key1']['nestkey']['subnestkey']
'value'

A few Dictionary Methods

There are a few methods we can call on a dictionary. Let’s get a quick introduction to a few of them:

Create a typical dictionary
d = {'key1':1,'key2':2,'key3':3}
Method to return a list of all keys 
d.keys()
dict_keys(['key1', 'key2', 'key3'])
Method to grab all values
d.values()
dict_values([1, 2, 3])

items() emthod return tuples of all items , we will discuss about tuple in next article.

d.items()
dict_items([('key1', 1), ('key2', 2), ('key3', 3)])

In summary, dictionaries in Python are a powerful and flexible data structure that allow you to store and organize data in key-value pairs. Dictionaries are unordered collections of objects, where each object is identified by a unique key. They are mutable, which means you can modify their contents by adding, removing, or updating key-value pairs. Additionally, the keys in a dictionary are unique, which means you cannot have multiple entries with the same key.

Mohan Kumar Pudasaini
Mohan Kumar Pudasaini
Data Analyst||Risk Analyst

Passionate about utilizing data to uncover valuable insights and drive actionable outcomes.

Related