0% found this document useful (0 votes)
10 views33 pages

Python Dictionary: Key-Value Basics

The document provides an overview of Python dictionaries, detailing their creation, manipulation, and various methods such as accessing items, updating, removing, and copying dictionaries. It explains key functions like len(), get(), update(), pop(), clear(), items(), values(), fromkeys(), and popitem(), along with examples for each. The document emphasizes the mutable nature of dictionaries and how they can be modified dynamically.

Uploaded by

Upasana Bhardwaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views33 pages

Python Dictionary: Key-Value Basics

The document provides an overview of Python dictionaries, detailing their creation, manipulation, and various methods such as accessing items, updating, removing, and copying dictionaries. It explains key functions like len(), get(), update(), pop(), clear(), items(), values(), fromkeys(), and popitem(), along with examples for each. The document emphasizes the mutable nature of dictionaries and how they can be modified dynamically.

Uploaded by

Upasana Bhardwaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Python Dictionary

• In Python, a dictionary is a collection that allows us to store data


in key-value pairs.
• Create a Dictionary
We create dictionaries by placing key:value pairs inside curly brackets
{}, separated by commas. For example,
Python Dictionary Length
• We can get the size of a dictionary by using the len() function.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}

# get dictionary's length


print(len(country_capitals)) # 3
Access Dictionary Items
• We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {

"United States": "Washington D.C.",


"Italy": "Rome",
"England": "London"
}

print(country_capitals["United States"]) # Washington D.C.

print(country_capitals["England"]) # London
• Dictionary get()

The get() method returns the value of the specified key in the dictionary.
The syntax of get() is:
The syntax of get() is:

[Link](key[, value])
get() Parameters

get() method takes maximum of two parameters:

key - key to be searched in the dictionary


value (optional) - Value to be returned if the key is not found. The default value is None.
Return Value from get()
get() method returns:

the value for the specified key if key is in the dictionary.


None if the key is not found and value is not specified.
value if the key is not found and value is specified.
[Link](key[, value])
scores = {
'Physics': 67,
'Maths': 87,
'History': 75
}

result = [Link]('Physics')

print(scores) # 67
person = {'name': 'Phill', 'age': 22}

print('Name: ', [Link]('name'))

print('Age: ', [Link]('age'))

# value is not provided


print('Salary: ', [Link]('salary'))

# value is provided
print('Salary: ', [Link]('salary', 0.0))
Change Dictionary Items

• Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring
to its key. For example,
country_capitals = {
"United States": "Washington D.C.,
"Italy": "Naples",
"England": "London"
}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

print(country_capitals)
OUTPUT:
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
Add Items to a Dictionary

• We can add an item to the dictionary by assigning a value to a new key (that does not exist in the
dictionary). For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}

# add an item with "Germany" as key and "Berlin" as its value


country_capitals["Germany"] = "Berlin"

print(country_capitals)
OUTPUT:
{'United States': 'Washington D.C.', 'Italy': 'Rome', ‘Germany': ‘Berlin'}
Python Dictionary update()

• The update() method updates the dictionary with the elements from another
dictionary object or from an iterable of key/value pairs.
• Syntax of Dictionary update()
The syntax of update() is:
[Link]([other])
update() Parameters

The update() method takes either a dictionary or an iterable object of key/value pairs
(generally tuples).

If update() is called without passing parameters, the dictionary remains unchanged.


• Return Value from update()
update() method updates the dictionary with elements from a dictionary object or an iterable object of
key/value pairs.
d = {1: "one", 2: "three"}
d1 = {2: "two"}

# updates the value of key 2


[Link](d1)

print(d)

d1 = {3: "three"}

# adds element with key 3


[Link](d1)

print(d)
Remove Dictionary Items

• We use the del statement to remove an element from the dictionary. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}

# delete item having "United States" key


del country_capitals["United States"]
print(country_capitals)

OUTPUT:
{'Italy': 'Naples'}
Dictionary pop()
The pop() method removes and returns an element from a dictionary having the given key.
• The syntax of pop() method is

[Link](key[, default])
• pop() Parameters
pop() method takes two parameters:

• key - key which is to be searched for removal


• default - value which is to be returned when the key is not in the dictionary.
Return value from pop()
• The pop() method returns:

• If key is found - removed/popped element from the dictionary


• If key is not found - value specified as the second argument (default)
• If key is not found and default argument is not specified - KeyError exception is raised
# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }

element = [Link]('Chemistry')

print('Popped Marks:', element)

# Output: Popped Marks: 72


Example 1: Pop an element from the dictionary

# random sales dictionary


sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = [Link]('apple')

print('The popped element is:', element)


print('The dictionary is:', sales)
OUTPUT:
The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}
Example 2: Pop an element not present from
the dictionary

# random sales dictionary


sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = [Link]('guava')

OUTPUT:
KeyError: 'guava'
Example 3: Pop an element not present from
the dictionary, provided a default value

# random sales dictionary


sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = [Link]('guava', 'banana')

print('The popped element is:', element)


print('The dictionary is:', sales)
OUTPUT:
The popped element is: banana
The dictionary is: {'orange': 3, 'apple': 2, 'grapes': 4}
Dictionary clear()

• The clear() method removes all items from the dictionary.


• clear() Syntax
• The syntax of the clear() method is:
[Link]()
Here, clear() removes all the items present in the dictionary.
clear() Parameters
The clear() method doesn't take any parameters.
clear() Return Value
The clear() method doesn't return any value.
# dictionary
numbers = {1: "one", 2: "two"}

# removes all the items from the dictionary


[Link]()

print(numbers)

# Output: {}
Dictionary copy()
• They copy() method returns a copy (shallow copy) of the dictionary.
• Syntax of Dictionary copy()
The syntax of copy() is:
[Link]()
copy() Arguments
The copy() method doesn't take any arguments.
copy() Return Value
This method returns a shallow copy of the dictionary. It doesn't modify
the original dictionary.
How copy works for
dictionaries?
original = {1:'one', 2:'two'}
new = [Link]()
print('Orignal: ', original)
print('New: ', new)

Output
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
Dictionary copy() Method Vs =
Operator
• When the copy() method is used, a new dictionary is created which is filled with a copy of the
references from the original dictionary.
• When the = operator is used, a new reference to the original dictionary is created.
• Example 2: Using = Operator to Copy Dictionaries
original = {1:'one', 2:'two'}
new = original
# removing all elements from the list
[Link]()
print('new: ', new)
print('original: ', original)
OUTPUT :
new: {}
original: {}
Here, when the new dictionary is cleared, the original dictionary is also cleared.
Using copy() to Copy
Dictionaries
original = {1:'one', 2:'two'}
new = [Link]()
# removing all elements from the list
[Link]()

print('new: ', new)


print('original: ', original)
OUTPUT:
new: {}
original: {1: 'one', 2: 'two'}
Here, when the new dictionary is cleared, the original dictionary remains unchanged.
Dictionary items()

• The items() method returns a view object that displays a list of dictionary's
(key, value) tuple pairs.
• Syntax of Dictionary items()
The syntax of items() method is:
[Link]()
items() Parameters
The items() method doesn't take any parameters.
Return value from items()
The items() method returns a view object that displays a list of a given
dictionary's (key, value) tuple pair.
Get all items of a dictionary
with items()
• marks = {'Physics':67, 'Maths':87}

• print([Link]())

• # Output: dict_items([('Physics', 67), ('Maths', 87)])


How items() works when a dictionary is
modified?
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

items = [Link]()

print('Original items:', items)

# delete an item from dictionary


del[sales['apple']]

print('Updated items:', items)


OUTPUT:
Original items: dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])
Updated items: dict_items([('orange', 3), ('grapes', 4)])
NOTE:
• The view object items doesn't itself return a list of sales items but it returns a view of sales's (key, value) pair.
• If the list is updated at any time, the changes are reflected on the view object itself, as shown in the above program.
Dictionary values()

• The values() method returns a view object that displays a list of all the
values in the dictionary.
• Syntax of Dictionary values()
The syntax of values() is:
• [Link]()
values() Parameters
• values() method doesn't take any parameters.
• Return value from values()
values() method returns a view object that displays a list of all values in a
given dictionary.
• Get all values from the dictionary
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

print([Link]())
Output
dict_values([2, 3, 4])
How values() works when a dictionary is
modified?

# random sales dictionary


sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

values = [Link]()

print('Original items:', values)

# delete an item from dictionary


del[sales['apple']]

print('Updated items:', values)


OUTPUT:
Original items: dict_values([2, 3, 4])
Updated items: dict_values([3, 4])
Dictionary fromkeys()

• The fromkeys() method creates a dictionary from the given sequence of keys and values.
• fromkeys() Syntax
• The syntax of the fromkeys() method is:
[Link](alphabets,number)
• Here, alphabets and numbers are the key and value of the dictionary. fromkeys() Parameters
The fromkeys() method can take two parameters:

alphabets - are the keys that can be any iterables like string, set, list, etc.
numbers (Optional) - are the values that can be of any type or any iterables like string, set, list, etc.
• fromkeys() Return Value
The fromkeys() method returns:

• a new dictionary with the given sequence of keys and values


• Note: If the value of the dictionary is not provided, None is assigned to the keys.
Python Dictionary fromkeys() with Key and
Value

# set of vowels
keys = {'a', 'e', 'i', 'o', 'u' }

# assign string to the value


value = 'vowel'

# creates a dictionary with keys and values


vowels = [Link](keys, value)

print(vowels)
OUTPUT: {'a': 'vowel', 'u': 'vowel', 'e': 'vowel', 'i': 'vowel', 'o': 'vowel'}
Example 2: fromkeys() without
Value
# list of numbers
keys = [1, 2, 4 ]

# creates a dictionary with keys only


numbers = [Link](keys)

print(numbers)
OUTPUT: {1: None, 2: None, 4: None}
Dictionary popitem()

• The syntax of popitem() is:


• [Link]()
Parameters for popitem() method
The popitem() doesn't take any parameters.
Return Value from popitem() method
The popitem() method removes and returns the (key, value) pair from the
dictionary in the Last In, First Out (LIFO) order.

Returns the latest inserted element (key,value) pair from the dictionary.
Removes the returned element pair from the dictionary.
Working of popitem() method

person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}

# ('salary', 3500.0) is inserted at the last, so it is removed.


result = [Link]()

print('Return Value = ', result)


print('person = ', person)

# inserting a new element pair


person['profession'] = 'Plumber'

# now ('profession', 'Plumber') is the latest element


result = [Link]()

print('Return Value = ', result)


print('person = ', person)

You might also like