0% found this document useful (0 votes)
2 views

12_Dictionary in Python

The document provides an overview of Python dictionaries, including their structure, properties, and how to access, update, and delete elements. It explains the uniqueness of keys, immutability requirements, and includes built-in functions and methods for dictionary manipulation. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

12_Dictionary in Python

The document provides an overview of Python dictionaries, including their structure, properties, and how to access, update, and delete elements. It explains the uniqueness of keys, immutability requirements, and includes built-in functions and methods for dictionary manipulation. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Dictionary in Python

Learning objective
• Python Dictionary
• Accessing Values in Dictionary
• Updating Dictionary
• Delete Dictionary Elements
• Properties of Dictionary Keys
• Built-in Dictionary Functions and Methods
Dictionary - Introduction
• A dictionary is a collection of data items which are unordered,
changeable and indexed.
• In Python dictionaries are written with curly brackets, and they
have keys and values.

• Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
braces.

• An empty dictionary without any items is written with just two


curly braces, like this: {}
Dictionary - Introduction
• Keys are unique within a dictionary while values may not be.

• The dictionary values can be of any type, but the keys must be of
an immutable data type such as strings, numbers, or tuples.

D = {'Name': 'John', 'Age': 25, ‘Degree': ‘Bachelor'};


Accessing values in Dictionary
• To access dictionary elements, you can use the familiar square
brackets along with the key to obtain its value.

D = {'Name': 'John', 'Age': 25, 'Degree': 'Bachelor'}


print (D['Name'])
print (D['Degree'])
print (D['Age’])

• If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error
Updating Dictionary
• You can update a dictionary by adding a new entry or a key-value
pair, modifying an existing entry, or deleting an existing entry.

D = {'Name': 'John', 'Age': 25, 'Degree': 'Bachelor','Marks':75}


print(D)
D['Age'] = 28; # update existing entry
print(D)
D['School'] = "DPS"; # Adding new entry
print(D)
Deleting Dictionary Elements
• You can either remove individual dictionary elements or clear the entire
contents of a dictionary or delete entire dictionary in a single operation.

D = {'Name': 'John', 'Age': 25, 'Degree': 'Bachelor','Marks':75}


print(D)
del D['Name'] # remove entry with key 'Name'
print(D)
D.clear() # remove all entries in dictionary
print(D)
del D # delete entire dictionary
# print(D)
# NameError: name 'D' is not defined
Properties of Dictionary Keys
• There are two important points to remember about dictionary
keys:
1. Each key must be unique in a dictionary. If a duplicate key is
assigned a new value, the old value is overwritten. When
duplicate keys encountered during assignment, the last
assignment wins.

2. Keys must be immutable data types, such as strings, numbers


or tuples as dictionary keys.
Properties of Dictionary Keys
Dict = {'Name':'John', 'Name':'Warner', 'Name' : 'David', 'Age':30,
'Experience':0}
print(Dict)

Dict2 = {'Name':['John', 'Warner','David'], 'Age':[30,32,35],


'Experience':[5,7,10]}
print(Dict2)
Built-in Dictionary Functions
• Python includes the following dictionary functions:
• len(dictionary) :Gives the total length of the dictionary. This would
be equal to the number of items in the dictionary.

• str(dictionary) : Produces a printable string representation of a


dictionary.

• type(variable) : Returns the type of the passed variable. If passed


variable is dictionary, then it would return a dictionary type.
Built-in Dictionary Functions
dict1 = {'name': 'Ahmed', 'age': 25, 'gender': 'M’}
print(len(dict1))
# Output: 3
print(str(dict1))
# Output: {'name': 'Ahmed', 'age': 25, 'gender': 'M'}
print(type(dict1))
# Output: <class 'dict'>
Built-in Dictionary Methods
• Python includes following dictionary methods:

• dict.clear() : Removes all elements of dictionary dict.


• dict.copy() : Returns a shallow copy of dictionary dict
• dict.fromkeys(iterable, value=None) : Create a new dictionary with
keys from sequence and assigns them all a specified value
(defaults to None).
• dict.get(key, default=None) : Returns the value for the specified
key if it exists, otherwise returns the default value
dict1 = {1: 'a', 2: 'b'}
dict1.clear()
print(dict1) # Output: {}

dict1 = {1: 'a', 2: 'b'}


copy_dict = dict1.copy()
print(copy_dict) # Output: {1: 'a', 2: 'b'}

keys = ('a', 'b', 'c')


dict1 = dict.fromkeys(keys, 0)
print(dict1) # Output: {'a': 0, 'b': 0, 'c': 0}

dict2 = {'name': 'Ahmed', 'age': 25}


print(dict2.get('name')) # Output: Ahmed
print(dict2.get('gender', 'N/A')) # Output: N/A
Built-in Dictionary Methods
• dict.items() : Returns a view object that displays a list of dictionary’s
key-value tuple pairs.

• dict.keys() : Returns a view object with all the dictionary's keys.

• dict.setdefault(key, default=None): Similar to get(), but will set


dict[key]=default if key is not already in dict

• dict.update(dict2) : Adds dictionary dict2's key values pairs to dict

• dict.values(): Returns a view object with all the dictionary's values.


dict1 = {'name': 'Ahmed', 'age': 26}
print(dict1.items()) # Output: dict_items([('name', 'Ahmed'), ('age', 26)])

print(dict1.keys()) # Output: dict_keys(['name', 'age'])

dict2 = {'name': 'Ahmed'}


age = dict2.setdefault('age', 26)
print(age) # Output: 26
print(dict2) # Output: {'name': 'Ahmed', 'age': 26}

dict1 = {'name': 'Ali', 'age': 30}


dict2 = {'age': 35, 'gender': 'Male'}
dict1.update(dict2)
print(dict1) # Output: {'name': 'Ali', 'age': 35, 'gender': 'Male'}

print(dict1.values()) # Output: dict_values(['Ali', 35, 'Male'])


You must have learnt:
• Python Dictionary
• Accessing Values in Dictionary
• Updating Dictionary
• Delete Dictionary Elements
• Properties of Dictionary Keys
• Built-in Dictionary Functions and Methods

You might also like