Objects of type dict are like lists except that "indices " need not be integers , they can be values of any immutable types . Since they are not ordered, the indices are referred as keys. Dictionaries can be thought of a key/value pairs where each key has a corresponding value. Literals of type dict are enclosed in curly braces and each element is written as a key followed by a colon followed by a value. Each key value pair is seperated by a comma.
For example:
>>>d = {1:red, 2:blue, 3:yellow , 4: orange, 5:black, 6: white}
>>>print d[1]
>>>red
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of immutable data type such as strings ,numbers, or tuples.
Operators on Dictionaries:
lend(d) : returns the number of stored entries i.e. the number of key/value pairs
del d[k] : deletes the key k together with its value
k in d : True if a key k exists in dictionary d
k not in d : True if a key deosn't exists in dictionary d
Methods on Dictionaries
1. Iterating over dictionary
for key in d:
print key
2. dict.setdefault(key,default=None)
will set dict[key] = default if key not in dict
3. dict.clear()
removes all elements of dictionary dict
4. dict.copy
returns a copy of dictionary dict
5. dict.items()
returns a list of dict's(key,value) pairs
6.dict.keys()
returns a list of keys
7.dict.values()
returns a list of values
No comments:
Post a Comment