Python Dictionaries:
Dictionaries are python data structures which store the data in key-value pairs. These are like Maps in other similar programming languages.
Dictionaries are not ordered unlike strings, Lists and Tuples.
Keys uniquely define the items in a python dictionary. So duplicate keys are not allowed.
Keys are unique but values are not.
Keys must be of immutable types like strings, numbers and tuples.
Dictionary can contain any type of values.
Creating a Dictionary :
Each key is separated from its value by a colon(:)
The items are separated by commas
All the above paired items are enclosed in curly braces.
watch video below to demonstrate python dictionaries:
Empty Dictionary:
An empty dictionary without any item is created with just two curly braces.{}
Example:
Dictionary containing items: (create and display)
Accessing values from Dictionary:
Values can be accessed using square brackets along with the key to obtain its value.
Example:
Both the print commands produces the corresponding values with keys "Name" and "Age".
If we attempt to access the data item which is not present in dictionary, we'll get error as
Updating Dictionary :
Dictionary can be updated by adding a new entry or a Key-Value pair, modifying an existing entry or deleting an existing entry :
Example:
Deleting Dictionary Element
You can delete either an individual item or entire content of a dictionary.
Entire dictionary can also be deleted in a single operation.
Example 1:
If we now want to print the items, An exception is raised because after the command del dict, dictionary does not exist.
Example 2:
Properties of Dictionary Keys:
1. More than one entry per key is not allowed i.e duplicate keys are not allowed. When duplicate keys are assigned, only the last assigned (latest) key exists.
2. Keys must be immutable. i.e you can use strings, numbers and Tuples as dictionary keys . others are not allowed.
Built-in Dictionary functions:
1. cmp : compares elements of both dict.
cmp ( dict1 , dict2)
2. len: Gives total length or the total number of elements in the dictionary.
len(dict)
3. str: produces a printable string representation of a dictionary.
str(dict)
4. type (variable) - returns the type of passed variable . If passed variable is dictionary, then it returns dictionary type.
Dictionary Methods:
Python uses following dictionary methods:
1. dict.clear( )
2. dict.copy( )
3. dict.fromkeys( )
4. dict.get(key, default = None)
5. dict.has_key(key)
6. dict.items( )
7. dict.keys()
8. dict.setdefault(key, default=None)
9. dict.update(dict2)
10. dict.values()
No comments:
Post a Comment