39.Dictionary -functions/methods
I.Python Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.
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.
cmp() Compares items of two dictionaries. (Not available in Python 3)
sorted() Return a new sorted list of keys in the dictionary.
Examples:
>>> squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>> len(squares)
6
>>> all(squares)
False
>>> any(squares)
True
>>> sorted(squares)
[0, 1, 3, 5, 7, 9]
II.Python Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used.
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new list of the dictionary's items in (key, value) format.
keys() Returns a new list of the dictionary's keys.
pop(key[,d]) 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.
popitem() Removes and returns last item. Raises KeyError if the dictionary is empty.
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).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new list of the dictionary's key and values
keys() items() and values() returns Keys, Values and Key:value pairs as lists
>>> D={1:10,2:20,3:30}
>>> D.keys()
dict_keys([1, 2, 3])
>>> D.values()
dict_values([10, 20, 30])
>>> D.items()
dict_items([(1, 10), (2, 20), (3, 30)])
>>> D={(1,2):10,(2,3):20}
>>> D.keys()
dict_keys([(1, 2), (2, 3)])
copy() method is used to create a copy of the dictionary. Note that assigning one dictionary object to another does not create a copy. It will create an alias only.
>>> D={1:10,2:20,3:30}
>>> C=D.copy()
>>> C
{1: 10, 2: 20, 3: 30}
Dictionary items in the sorted order of values
Python Dictionary Comprehension
This code is equivalent to
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
Dictionary Membership Test
>>> C=D.copy()
>>> C
{1: 10, 2: 20, 3: 30}
Merging Dictionaries
Two dictionaries can be merged in to one by using update( ) method. It merges the keys and values of one dictionary into another and overwrites values of the same key.
>>> d1={1:10,2:20,3:30}
>>> d2={2:100,4:40,5:50}
>>> d1.update(d2)
>>> d1
{1: 10, 2: 100, 3: 30, 4: 40, 5: 50}
>>> d1.update(d2)
>>> d1
{1: 10, 2: 100, 3: 30, 4: 40, 5: 50}
>>> marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
>>> marks
{'Math': 0, 'English': 0, 'Science': 0}
setdefault function will set a default return value if the key is not prsent
>>> C
{1: 10, 2: 20, 3: 30}
>>> C.setdefault(2,-1)
20
>>> C
{1: 10, 2: 20, 3: 30}
>>> C.setdefault(4,40)
40
>>> C
{1: 10, 2: 20, 3: 30, 4: 40}
Traversing a dictionary
items() method return the dictionary key and values.But a for loop can be used effectively to traverse the dictionary and access each item.
>>> D={2:20,1:30,3:40}
for k in D:
print(k)
This will print keys
2
1
3
The following loop will print both keys and values.
>>> for k in D:
print(k,D[k])
2 20
1 30
3 40
Use of tuple variables is a powerful method
>>> for (k,v) in D.items():
print(k,v)
2 20
1 30
3 40
Displaying the dictionary in the sorted order of keys
We can list the Dictionary items in the order of keys
>>>D={2:20,1:30,3:40}
>>> sortkeys=sorted(D.keys())
>>> sortkeys
[1, 2, 3]
>>> for key in sortkeys:
print(key,D[key])
1 30
2 20
3 40
We can also use OrderedDict method from collections
from collections import OrderedDict
D={2:20,1:30,3:40}
dict = {'ravi': '10', 'rajnish': '9','yash': '2','sanjeev': '15', 'suraj': '32'}
D_ord = OrderedDict(sorted(D.items()))
print(D_ord)
dict_ord = OrderedDict(sorted(dict.items()))
print(dict_ord)
output:
OrderedDict([(1, 30), (2, 20), (3, 40)])
OrderedDict([('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')])
dict = {'ravi': 10, 'rajnish': 9,'sanjeev': 15, 'yash': 2, 'suraj': 32}
print(dict)
dictionary_keys = list(dict.keys())
sorted_dict = {dictionary_keys[i]: sorted(
dict.values())[i] for i in range(len(dictionary_keys))}
print(sorted_dict)
output:
{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
>>> squares = {x: x*x for x in range(6)}
>>> print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Output{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
# Dictionary Comprehension with if conditional
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}
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 the membership test is only for the keys and not for the values.
# Membership Test for Dictionary Keys
>>>squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>>print(1 in squares)
True
>>>print(2 not in squares)
False
>>>print(49 in squares)
False
Reverse Dictionary Lookup
Doing a reverse dictionary lookup returns a list containing each key in the dictionary that maps to a specified value.
D={'a': 1, 'b': 3, 'c': 1, 'd': 2}
lookup_value = 1
all_keys = []
for key, value in D.items():
if(value == lookup_value):
all_keys.append(key)
print(all_keys)
output:
['a', 'c']
Comments
Post a Comment