Python Dictionary


Introduction to Dictionary

A dictionary in python is a collection of key:value pairs.

Curly brackets “{}” are used for the construction of the dictionary. The key and its value are separated by the colon(:) and each pair is separated by the comma.

A key in a dictionary can be any immutable data type only, for example, integer, string, or tuple. A value in a dictionary can be any data type, mutable or immutable, for example, integer, string, list, set, tuple, or dictionary itself.

In dictionaries, values can be accessed by using the keys instead of indexes.

In [1]:
dict = {'key1':'value1','key2':'value2'}
print(dict)
{'key1': 'value1', 'key2': 'value2'}

Value in the dictionary can be of any data type.

In [2]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

Accessing value with the key.

In [3]:
print(emp_details['first_name'])
print(emp_details['bill'])
Tim
200.2

Key can be any immutable data type. Dictionary with key as integer, string, and tuple.

In [4]:
numbers= {1:'One', 2:'Two', 'Three':'Three', ('Four','Five'):['Four','Five']}

Accessing the values.

In [5]:
print(numbers[1])
print(numbers[('Four','Five')])
One
['Four', 'Five']

Returns error on creating a dictionary using the list as a key.

In [6]:
numbers= {[1,2]:['One','Two']}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ee95441c4a0a> in <module>
----> 1 numbers= {[1,2]:['One','Two']}

TypeError: unhashable type: 'list'

Characteristics of a Dictionary

Let us look at the characteristics of the dictionary one by one:

CharacteristicMeaning
MutableThis means that we can change, add and remove the items stored within the dictionary.
UniqueThe keys in the dictionary cannot be duplicated.
OrderedFrom Python 3.7 and higher versions, dictionaries are ordered.
Characteristics of a Dictionary

Dictionaries are Ordered now

Dictionaries are ordered from python version 3.7, and before that dictionaries used to be unordered.

Changeable

Dictionaries are changeable, means we can change, add or remove items in the dictionary any time.

Dealing with duplicates

The Python Dictionary does not allow having two or more items with the same key. If we try to create a dictionary with more than one item having the same key, then it will keep only one and all others will get discarded.

The key ‘first_name’ is repeated twice in the below dictionary. It keeps only the latest one.

In [1]:
emp_details = {'first_name':'Tim',
               'last_name':'Smith',
               'first_name':'Rocky'}
In [2]:
emp_details
Out[2]:
{'first_name': 'Rocky', 'last_name': 'Smith'}

Dictionary keys are Special

Dictionary keys are special because of these properties:

1. Unique: The key of the dictionary cannot be repeated. In case we repeat the key, the old value of that key will be replaced by the new value.

In the below example, the key “1” is replaced with the value “Three”.

In [1]:
numbers= {1:'One', 2:'Two', 1:'Three'}
print(numbers)
{1: 'Three', 2: 'Two'}

2. Only mutable elements: The key in the dictionary can have only mutable elements like number, string list. Immutable elements like the list or the dictionary itself are not allowed as the key.

Number, string and tuple as the key.

In [1]:
numbers= {1:"One", "TWO":"Two", ("Three", "Four"):["Three", "Four"]}
print(numbers)
{1: 'One', 'TWO': 'Two', ('Three', 'Four'): ['Three', 'Four']}

List as key result in error.

In [2]:
numbers= {["Three", "Four"]:["Three", "Four"]}
print(numbers)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-ba8bf1a433ee> in <module>
----> 1 numbers= {["Three", "Four"]:["Three", "Four"]}
      2 print(numbers)

TypeError: unhashable type: 'list'

Dictionary as key result in error.

In [3]:
numbers= {{"Three": "Four"}:["Three", "Four"]}
print(numbers)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-2fbad162ce84> in <module>
----> 1 numbers= {{"Three": "Four"}:["Three", "Four"]}
      2 print(numbers)

TypeError: unhashable type: 'dict'

Nested Dictionary

A nested dictionary means when we have a dictionary inside another dictionary. We can have multiple levels of dictionaries inside the dictionaries.

Ways to create Nested Dictionary

1. Directly nesting a new level inside the existing level.

In [1]:
nested_dictionary = {
  "Bill" : {
    "age" : 55,
    "gender" : "Male"
  },
  "Steve" : {
    "age" : 57,
    "gender" : "Male"
  },
    "Lisa" : {
    "age" : 52,
    "gender" : "Female"
  }
}

print(nested_dictionary)
{'Bill': {'age': 55, 'gender': 'Male'}, 'Steve': {'age': 57, 'gender': 'Male'}, 'Lisa': {'age': 52, 'gender': 'Female'}}

2. Create single level dictionaries and then create a parent dictionary that contains single level dictionaries.

In [1]:
Bill = {
    "age" : 55,
    "gender" : "Male"}

Steve = {
    "age" : 57,
    "gender" : "Male"}

Lisa = {
    "age" : 52,
    "gender" : "Female"
  }

nested_dictionary = {
  "Bill" : Bill,
  "Steve" : Steve,
    "Lisa" : Lisa
}

print(nested_dictionary)
{'Bill': {'age': 55, 'gender': 'Male'}, 'Steve': {'age': 57, 'gender': 'Male'}, 'Lisa': {'age': 52, 'gender': 'Female'}}

Access items of Nested Dictionary

To access the inner child. We first need to access the parent and keep on moving level by level.

In [1]:
employee_details = {
  "Bill" : {
    "age" : 55,
    "gender" : "Male"
  },
  "Steve" : {
    "age" : 57,
    "gender" : "Male"
  },
    "Lisa" : {
    "age" : 52,
    "gender" : "Female"
  }
}

print(employee_details["Bill"]["age"])
print(employee_details["Lisa"]["age"])
print(employee_details["Steve"])
55
52
{'age': 57, 'gender': 'Male'}

Sort Dictionary

Python has the in-built function sorter() to sort the elements of the dictionary. It returns us a sorted list of keys in case we pass keys as argument and a sorted list of values in case we pass dict.values() as argument. In case, the argument is dict.items(), then it returns a list with tuples of key and value.

In [1]:
numbers= {1:'One', 5:'Five', 8:'Eight'}
print(numbers)
{1: 'One', 5: 'Five', 8: 'Eight'}

Sorting as per key.

In [2]:
print(sorted(numbers))
[1, 5, 8]

Sorting as per value.

In [3]:
print(sorted(numbers.items()))
[(1, 'One'), (5, 'Five'), (8, 'Eight')]

Sorting as per key.

In [4]:
print(sorted(numbers.values()))
['Eight', 'Five', 'One']

The type() function

At any stage in our program, we may need to check whether the variable is a dictionary or not, we can use the type() function for this purpose. If the type of the variable is a dictionary, then the type() function will return the ‘dict’ keyword.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Smith', 'emp_id':200, 'programming_languages':['Python','C++','Java']}
print(type(emp_details))
<class 'dict'>

The dict() Constructor

A dictionary can also be created using the dict() constructor. Here we have to pass the comma separated key-value pair in the pattern “key = value”.

In [1]:
emp_details = dict(first_name = 'Tim', last_name = 'Cook', emp_id = 200, bill = 200.20)
print(emp_details)
print(type(emp_details))
{'first_name': 'Tim', 'last_name': 'Cook', 'emp_id': 200, 'bill': 200.2}
<class 'dict'>

Dictionary Length

The len() function can be used to determine how many items we have in the dictionary.

In [1]:
numbers= {1:"One", 2:"Two", 3:"Three"}
print(len(numbers))
3

Membership Test

Membership operators in and not in are used to check whether a key is present in the dictionary or not. Note: This can be used to check the key only, not the values in the dictionary.

In [1]:
numbers= {1:"One", 2:"Two", 3:"Three"}

print(1 in numbers)
print(2 not in numbers)
True
False

References

  1. Dictionaries in Python
  2. Python – Nested Dictionaries