Keys and Values over Dictionary Objects in Python
* Important points to remember while dealing with Dictionary
Objects in Python are the following :
1) One can use any type of datatype while dealing with any value
for a Dictionary Object in Python
2) A value can be a number , string , list , tuple or any other
dictionary object in Python
3) Keys in Python should obey the following rules
*** point-1 ***
Keys should be always unique . Duplicate Keys are not allowed in
Python . And If the user/programmer enters the same key again over the existing
dictionary , then the old key would be overwritten and only the new key would
be available . One can consider the following example for considering the case
of uniqueness of a Key in Python
emp =
{
'Data1':100,
'Data2':200,
'Data1':300
}
If someone wants to print the contents of the dictionary object
after the object has been created , then one would find that the values within
the dictionary for the data item which has been entered twice that is
"Data1" which is entered twice in the case would be printed only once
as a single data item can only exist once , and this data item would have the
higher value of the object .
print(emp)
Result :
{
'Data1':300,
'Data2':200
}
Here , one would be noticing that the values for the data item
are replaced with the one which has a higher value over the other data item
object which means that the dictionary object gives precedence to that sub-data
item within it to exist within it which has a higher value for the same /
duplicate key .
The screenshot for the above code is as given below :
*** point-2 ***
Keys should be immutable in nature . For example , one can use a
number , a string or a tuple as key since the keys are immutable in nature .
One cannot use lists or dictionaries as Keys . If as such , Keys are used then
one will get 'TypeError' . One can consider the following example in case of a
Dictionary Object :
emp =
{
[
'Data1']:100,
'Data2':200,
'Data1':300
}
# Here , upon compilation and execution of the code one would get to see that for the list element 'Data1' we get an error in the output section . This is because, as mentioned above, the key item should only be a number , string or a tuple in nature .
No comments:
Post a Comment