--Originally published at Hector Martinez Alcantara
A dictionary is like the lists, is a list of elements of different types, or the same type identified by a special name.
This is the sintaxis:
dict = {'identifier1': 'Element1', 'identifier2': 2, 'identifier3': 'Element3'}
You can access to a dictionary by the identifier of the element.
print(dict['identifier1']) #Result: "Element 1" print(dict['identifier2']) #Result: 2
You can update a dictionary by rewriting it, or by simply assigning a value to the element:
dict['identifier1']= "New value"
To delete an element of the dictionary, you have to use the reserved word del or the method clear to delete all the elements in the dictionary:
del dict['identifier1'] dict.clear()
Python includes the following dictionary functions −
Function with Description |
cmp(dict1, dict2)
Compares elements of both dict. |
len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. |
str(dict)
Produces a printable string representation of a dictionary |
type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. |
Python includes following dictionary methods
Methods with Description |
dict.clear()
Removes all elements of dictionary dict |
dict.copy()
Returns a shallow copy of dictionary dict |
dict.fromkeys()
Create a new dictionary with keys from seq and values set to value. |
dict.get(key, default=None)
For key key, returns value or default if key not in dictionary |
dict.has_key(key)
Returns true if key in dictionary dict, false otherwise |
dict.items()
Returns a list of dict‘s (key, value) tuple pairs |
dict.keys()
Returns list of dictionary dict’s keys |
dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict |
dict.update(dict2)
Adds dictionary dict2‘s key-values pairs to dict |
dict.values()
Returns list of dictionary dict‘s values |
Thanks for reading, and special thanks as usual to Tutorialspoint who always have good information.