Python Dictionary:

While learning Python for data science, a dictionary is defined as a collection of unordered data values. Unlike other data types, Dictionary holds a key: value pair. This makes the dictionary more optimized. Each key-value pair in Python are separated by colon(:) and the keys are separated by a comma.

A python dictionary is similar to a standard dictionary which we use. The dictionary should contain keys that are unique and immutable (strings, tuples, integers), and the key values can be duplicated and of any type.

Important point- Polymorphism is prohibited in keys in a dictionary.

Creation of a Dictionary:

Placement of sequence of elements within curly braces {} with comma as a separator leads to the creation of a dictionary. As already discussed earlier, a dictionary has a key and a pair of key: value. Values are mutable, but keys are immutable and non-repeatable.

Built-in function dict() can be used for the creation of a dictionary. Two curly braces {} can be used to create an empty dictionary.

Point to remember while working in python for data science – Keys in a dictionary are case sensitive, i.e. same name with different cases will be treated as two distinct keys.

# Creating an empty Dictionary

Dict = {}

print(“Empty Dictionary: “)

print(Dict)

# Creating a Dictionary

#with Integer Keys

Dict = {1: ‘Python’, 2: ‘Is’, 3: ‘Best’}

print(“\nDictionary using Integer Keys: “)

print(Dict)

#Creating a Dictionary

# with Mixed keys

Dict = {‘Name’: ‘PST’, 1: [1, 2, 3, 4]}

print(“\nDictionary using Mixed Keys: “)

print(Dict)

#Creation of  Dictionary

#using dict() method

Dict = dict({1: ‘Python’, 2: ‘Is’, 3:’Best’})

print(“\nDictionary using dict(): “)

print(Dict)

# Creating a Dictionary

#with each item as a Pair

Dict = dict([(1, ‘PST’), (2, ‘Analytics’)])

print(“\nDictionary using each item as a pair: “)

print(Dict)

Output:

Empty Dictionary:

{}

Dictionary using Integer Keys:

{1: ‘Python’, 2: ‘Is’, 3: ‘Best’}

Dictionary using Mixed Keys:

{1: [1, 2, 3, 4], ‘Name’: ‘PST’}

Dictionary with the use of dict():

{1: ‘Python’, 2: ‘Is’, 3: ‘Best’}

Dictionary with each item as a pair:

{1: ‘PST’, 2: ‘Analytics’}

 

Nested Dictionary:

Understanding Dictionaries in Python for Data Science - PST Analytics

# Creating a Nested Dictionary

#as shown in the below image

Dict = {1: ‘PST’, 2: ‘For’,

3:{‘A’ : ‘Welcome’, ‘B’ : ‘To’, ‘C’ : ‘PST’}}

print(Dict)

Output:

{1: ‘PST’, 2: ‘For’, 3: {‘A’: ‘Welcome’, ‘B’: ‘To’, ‘C’: ‘PST’}}

 

Adding Elements to a Dictionary:

There are multiple ways to add elements in a dictionary. We can add elements one by one by defining value along with the key( dict[Key] = ‘Value’. To alter or update an existing value, use the function update(). We can add nested key values to an already existing dictionary.

Point to remember while working on python for data science- While adding a value if we add a value which already exists it will get updated or else a new key is created containing the new value.

# Creating an empty Dictionary

Dict = {}

print(“Empty Dictionary: “)

print(Dict)

# Adding elements one at a time

Dict[0] = ‘PST’

Dict[2] = ‘For’

ict[3] = 1

print(“\nDictionary after adding 3 elements: “)

print(Dict)

# Adding set of values

# to a single Key

Dict[‘Value_set’] = 2, 3, 4

print(“\nDictionary after adding 3 elements: “)

print(Dict)

# Updating existing Key’s Value

Dict[2] = ‘Analytics’

print(“\nUpdated key value: “)

print(Dict)

# Adding Nested Key value to Dictionary

Dict[5] = {‘Nested’ :{‘1’ : ‘Life’, ‘2’ : ‘Python’}}

print(“\nAdding a Nested Key: “)

print(Dict)

 

Output:

Empty Dictionary:

{}

Dictionary after adding 3 elements:

{0: ‘PST’, 2: ‘For’, 3: 1}

Dictionary after adding 3 elements:

{0: ‘PST’, 2: ‘For’, 3: 1, ‘Value_set’: (2, 3, 4)}

Updated key value:

{0: ‘PST’, 2: ‘Analytics’, 3: 1, ‘Value_set’: (2, 3, 4)}

Adding a Nested Key:

{0: ‘Geeks’, 2: ‘Analytics’, 3: 1, 5: {‘Nested’: {‘1’: ‘Life’, ‘2’: ‘Python’}}, ‘Value_set’: (2, 3, 4)}

Accessing Elements from Dictionary:

Key name can be used to access items from a dictionary. Keys are used inside square brackets to access items. Another way of accessing items is to use the get() function.

# Accesing an element from a Dictionary

# Creating a Dictionary

Dict = {1: ‘PST’, ‘name’: ‘For’, 3: ‘Python’}

# accessing a element using key

print(“Acessing a element using key:”)

print(Dict[‘name’])

# accessing a element using key

print(“Acessing a element using key:”)

print(Dict[1])

# accessing a element using get()

# method

print(“Acessing a element using get:”)

print(Dict.get(3))

Output:

Acessing a element using key:

For

Acessing a element using key:

PST

Acessing a element using get:

Python

Removing Elements in Dictionary:

The del() function can be used to delete keys from a dictionary in python for data science. The function del() can be used to either delete a specific key or the entire dictionary. The pop() and popitem() functions can be used to delete either specific or random keys from a dictionary. Another important function clear() can be used to clear up the whole dictionary. In the case of a nested dictionary we should provide the nested key and the particular key both to be deleted from the dictionary.

Extra point: del dict() can be used to remove the whole dictionary. Printing a deleted dictionary will generate an error.

# Initial Dictionary

Dict = { 5 : ‘Welcome’, 6 : ‘To’, 7 : ‘PST’,

‘A’ : {1 : ‘PST’, 2 : ‘For’, 3 : ‘Python’},

‘B’ : {1 : ‘Python’, 2 : ‘Life’}}

print(“Initial Dictionary: “)

print(Dict)

# Deleting a Key value

del Dict[6]

print(“\nDeleting a specific key: “)

print(Dict)

# Deleting a Key from

# Nested Dictionary

del Dict[‘A’][2]

print(“\nDeleting a key from Nested Dictionary: “)

print(Dict)

# Deleting a Key

# using pop()

Dict.pop(5)

print(“\nPopping specific element: “)

print(Dict)

# Deleting an arbitrary Key-value pair

# using popitem()

Dict.popitem()

print(“\nPops an arbitrary key-value pair: “)

print(Dict)

# Deleting entire Dictionary

Dict.clear()

print(“\nDeleting Entire Dictionary: “)

print(Dict)

Output:

Initial Dictionary:

{‘A’: {1: ‘PST’, 2: ‘For’, 3: ‘Python’}, ‘B’: {1: ‘Python’, 2: ‘Life’}, 5: ‘Welcome’, 6: ‘To’, 7: ‘PST’}

Deleting a specific key:

{‘A’: {1: ‘PST’, 2: ‘For’, 3: ‘Python’}, ‘B’: {1: ‘Python’, 2: ‘Life’}, 5: ‘Welcome’, 7: ‘PST’}

Deleting a key from Nested Dictionary:

{‘A’: {1: ‘PST’, 3: ‘Python’}, ‘B’: {1: ‘Python’, 2: ‘Life’}, 5: ‘Welcome’, 7: ‘PST’}

Popping specific element:

{‘A’: {1: ‘PST’, 3: ‘Python’}, ‘B’: {1: ‘Python’, 2: ‘Life’}, 7: ‘Geeks’}

Pops an arbitrary key-value pair:

{‘B’: {1: ‘Python’, 2: ‘Life’}, 7: ‘PST’}

Deleting Entire Dictionary:

{}

Methods in Dictionary:

Understanding Dictionaries in Python for Data Science - PST Analytics

If you want to learn more, you can check this and this.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.