Python Tutorial: Dictionary Function & Methods

Wednesday, 12 August 2020

Dictionary Function & Methods

Python Dictionary and Function Methods

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

Function

Description

all()

Return True if all keys of the dictionary are True (or if the dictionary is empty).

any()

Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len()

Return the length (the number of items) in the dictionary.

sorted()

Return a new sorted list of keys in the dictionary.

For Example :

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> print(all(StudentMarks))

True

>>> print(any(StudentMarks))

True

>>> print(len(StudentMarks))

3

>>> print(sorted(StudentMarks))

['Ankita', 'Shikha', 'Vanshika']

clear()

Removes all items from the dictionary.

For Example :

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> StudentMarks

{'Ankita': 453, 'Vanshika': 444, 'Shikha': 453}

>>> StudentMarks.clear()

>>> StudentMarks

{}

copy()

Returns a shallow copy of the dictionary.

For Example :

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> SMarks=StudentMarks.copy()

>>> SMarks

{'Ankita': 453, 'Vanshika': 444, 'Shikha': 453}

fromkeys (seq[, v])

Returns a new dictionary with keys from seq and value equal to v (defaults to None).

For Example

# Dictionary Methods

marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}

print(marks)

for item in marks.items():

    print(item)

# Output: ['English', 'Math', 'Science']

print(list(sorted(marks.keys())))

Output

{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']

get(key[,d])

Returns the value of the key. If the key does not exist, returns d (defaults to None).

person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# value is not provided
print('Salary: ', person.get('salary'))
# value is provided
print('Salary: ', person.get('salary', 0.0))
Output
Name:  Phill
Age:  22
Salary:  None
Salary:  0.0

items()

Return a new object of the dictionary's items in (key, value) format.

For Example :

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> StudentMarks

{'Ankita': 453, 'Vanshika': 444, 'Shikha': 453}

>>> StudentMarks.items()

dict_items([('Ankita', 453), ('Vanshika', 444), ('Shikha', 453)])

keys()

Returns a new object of the dictionary's keys.

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> StudentMarks

Output

{'Ankita': 453, 'Vanshika': 444, 'Shikha': 453}

>>> StudentMarks.keys()

Output

dict_keys(['Ankita', 'Vanshika', 'Shikha'])

pop(key[, default])

Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.

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

For Example :

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> element = StudentMarks.pop('Vanshika')

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

Output

The popped element is: 444

>>> print('The dictionary is:', StudentMarks)

Output

The dictionary is: {'Ankita': 453, 'Shikha': 453}

popitem()

Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.

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

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

>>> result = person.popitem()

>>> print('Return Value = ', result)

Output

Return Value =  ('salary', 3500.0)

>>> print('person = ', person)

Output

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

>>> person['profession'] = 'Plumber'  # inserting a new element pair
>>> result = person.popitem() # now ('profession', 'Plumber') is the latest element

>>> print('Return Value = ', result)

Output

Return Value =  ('profession', 'Plumber')

>>> print('person = ', person)

Output

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

setdefault(key[,d])

Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).

For Example

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

age = person.setdefault('age')

print('person = ',person)

print('Age = ',age)

Output

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

Age =  22

Example 2: How setdefault() works when key is not in the dictionary?

person = {'name': 'Phill'}

 

# key is not in the dictionary

salary = person.setdefault('salary')

print('person = ',person)

print('salary = ',salary)

 

# key is not in the dictionary

# default_value is provided

age = person.setdefault('age', 22)

print('person = ',person)

print('age = ',age)

Output

person =  {'name': 'Phill', 'salary': None}

salary =  None

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

age =  22

update([other])

Updates the dictionary with the key/value pairs from other, overwriting existing keys.

For Example

d = {1: "First", 2: "Third"}

d1 = {2: "Second"}

# updates the value of key 2

d.update(d1)

print(d)

d1 = {3: " Third "}

# adds element with key 3

d.update(d1)

print(d)

Output

{1: 'one', 2: 'two'}

{1: 'one', 2: 'two', 3: 'three'}

values()

Returns a new object of the dictionary's values.

For Example

>>> StudentMarks={"Ankita":453, "Vanshika": 444, "Shikha": 453}

>>> StudentMarks.values()

Output

dict_values([453, 444, 453])

Example : How values() works when dictionary is modified?

# random sales dictionary

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

values = sales.values()

print('Original items:', values)

# delete an item from dictionary

del[sales['apple']]

print('Updated items:', values)

 

 

No comments:

Post a Comment