Python Devlopment






Built-in Dictionary Methods



There are some built-in methods which are included in Python are as follows;

Sr. No Function Description
1 all(dict) It is a boolean type function, which returns True if all keys of dictionary are true( or the empty dictionary)
2 any(dict) It is also boolean type function, which returns True if any key of the dictionary is True. It returms false if the dictionary is empty.
3 len(dict) It returns number of items(length) in the dictionary
4 cmp(dict1,dict2) It compares the items of two dictionary
5 sorted(dict) It returns the sorted list of keys
6 str(dict) It produces a printable string representation of the dictionary
7 dict.clear() It deletes all the items in a dictionary at once
8 dict.copy() It returns a copy of the dictionary
9 dict.fromkeys() It creates a new dictionary with keys from sequence and values set to values
10 dict.get(key, default=None) For key key, returns value or default if key not in dictionary
11 dict.has_key(key) It finds the key in the dictinary; returns True if found and False otherwise
12 dict.items() It returns a list of entire key:value pair of dictinary
13 dict.keys() It returns the list of all the keys in the dictionary
14 dict.update(dist2) It adds the item from dict2 to dict
15 dict.values() It returns all the values in the dictionary.

 

Example

>>> cubes={1:1, 2:8, 3:27, 4:64, 5:125, 6:216}
>>> all(cubes)
True
>>> any(cubes)
True
>>> sorted(cubes)
[1, 2, 3, 4, 5, 6]
>>> str(cubes)
'{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}'
>>> cubes.items()
dict_items([(1, 1), (2, 8), (3, 27), (4, 64), (5, 125), (6, 216)])
>>> cubes.keys()
dict_keys([1, 2, 3, 4, 5, 6])
>>> cubes.values()
dict_values([1, 8, 27, 64, 125, 216])
>>> len(cubes)
6
>>>