Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Dictionary in Python

The document discusses Python dictionaries. It explains that dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. It demonstrates how to create, access, modify, delete elements from dictionaries and built-in functions like len() and sorted() that can operate on dictionaries. Dictionary comprehensions provide a concise way to create dictionaries from iterables. Membership testing and iteration are also covered.

Uploaded by

Rupesh Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Dictionary in Python

The document discusses Python dictionaries. It explains that dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. It demonstrates how to create, access, modify, delete elements from dictionaries and built-in functions like len() and sorted() that can operate on dictionaries. Dictionary comprehensions provide a concise way to create dictionaries from iterables. Membership testing and iteration are also covered.

Uploaded by

Rupesh Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 21

PYTHON-5

DICTIONARY
Dictionary in Python

 Python dictionary is an unordered collection of items.


 A dictionary has a { key: value } pair , while other
compound data types have only value as an element.
 Dictionaries are optimized to retrieve values when the
key is known.
How to create a dictionary?

 Creating a dictionary is as simple as placing items inside


curly braces { } separated by comma.
 An item has a key and the corresponding value
expressed as a pair, key: value.
 While values can be of any data type and can repeat.
 Keys must be of immutable type
(string, number or tuple with immutable elements) and
must be unique.
Creating a dictionary
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict() –in-build function
my_dict = dict({1:'apple', 2:'ball'})
How to access elements
from a dictionary?
 While indexing is used with other container types to
access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.
 The difference while using get() is that it
returns None instead of KeyError, if the key is not
found.
Accessing elements from a
dictionary
my_dict = {'name':'Jack', 'age': 26}

print(my_dict['name'])
# Output: Jack

print(my_dict.get('age'))
# Output: 26
How to change or add
elements in a dictionary?
 How to change or add elements in a dictionary?
 Dictionary are mutable. We can add new items or
change the value of existing items using assignment
operator.
 If the key is already present, value gets updated, else a
new key: value pair is added to the dictionary.
Changing or adding elements in a
dictionary?
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
#Output: {'age': 27, 'name': 'Jack'}
# add item
my_dict['address'] = 'Downtown'
print(my_dict)

# Output: {'address': 'Downtown', 'age': 27, 'name':


'Jack'}
How to delete or remove
elements from a dictionary?
 We can remove a particular item in a dictionary by
using the method pop(). This method removes as item
with the provided key and returns the value.
 The method, popitem() can be used to remove and
return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using
the clear() method.
 We can also use the del keyword to remove individual
items or the entire dictionary itself.
Removing element/Dictionary
using pop(),popitem(),del,clear()

 # create a dictionary  # delete a particular item


 squares = {1:1, 2:4, 3:9, 4:16,  del squares[5]
5:25}
 print(squares)
 # remove a particular item
 # Output: {2: 4, 3: 9}
 print(squares.pop(4))
 # remove all items
 # Output: 16
 squares.clear()
 print(squares)
 # Output: {1: 1, 2: 4, 3: 9, 5: 25}
 print(squares)
 # remove an arbitrary item  # Output: {}
 print(squares.popitem())  # delete the dictionary itself
 # Output: (1, 1)  del squares
 print(squares)  print(squares)
 # Output: {2: 4, 3: 9, 5: 25}  # Throws Error#
Python Dictionary Methods
Creating dictionary
using .fromkeys
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
for item in marks.items():
print(item)

print(list(sorted(marks.keys())))
# Output: ['English', 'Math', 'Science']
Python Dictionary Comprehension

 Dictionary comprehension is an elegant and concise way


to create new dictionary from an iterable in Python.
 Dictionary comprehension consists of an expression pair
(key: value) followed by for statement inside curly
braces {}.
Python Dictionary
Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The code is equivalent to :
squares = {}
for x in range(6):
squares[x] = x*x
Python Dictionary
Comprehension
odd_squares = {x: x*x for x in
range(11) if x%2 == 1}
print(odd_squares)

# Output: {1: 1, 3: 9, 5: 25, 7: 49,


9: 81}
Dictionary Membership Test

 We can test if a key is in a dictionary or not using the


keyword in. Notice that membership test is for keys
only, not for values.
Dictionary Membership Test

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


print(1 in squares)
# Output: True

print(2 not in squares)


# Output: True

# membership tests for key only not value


print(49 in squares)
# Output: False
Iterating Through a Dictionary

 Using a for loop we can iterate though each key in a


dictionary.
 Example :

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


for i in squares:
print(squares[i])
Built-in Functions with
Dictionary
Using built-in function

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


print(len(squares))
# Output: 5

print(sorted(squares))
# Output: [1, 3, 5, 7, 9]
n k s
Tha

You might also like