Dictionaries in Python
A dictionary is a data set of key-value pairs. It provides a way to map pieces of data to each other and allows for quick access to values associated with keys.
In Python, dictionaries are dynamic and mutable, which
means they can change.
Note: As of Python version 3.7, dictionaries are
ordered based on insertion, but this is not the case in previous versions.
dictionary_name = { key1:
value1, key2: value2, key3: value3 }
Each entry in a dictionary
is a key-value pair. Each pair is separated by a comma.
Dictionary keys must be
immutable types such as numbers and strings because keys should not change.
Keys cannot be lists because lists are mutable, and it will raise a TypeError.
Values can be any type,
such as strings, numbers, lists, and even other dictionaries.
Dictionary Creation:
1.dic = {}
2.x = dict()
A same dictionary can be created as below:
t1 = {1:'python',2:'Java',3:'Hadoop','4:'Aws'}
Here {1,2,3} are keys and {'python','Java','Hadoop','Aws'} are values
To access a dictionary use below:
print(t1[1] ) #Display Python
When a value is retrieved from a key that does not
exist, Key-Error is raised. If a value is assigned to a key that
doesn’t exist, the new key-value pair will be added. If a value is assigned to
an existing dictionary key, it replaces the existing value.
To iterate the dictionary, we have several ways to do that
var = {'john':10.5,'Adam':59.4,'Rey':34.2,'Tom':22.6}
To add new entry to a dictionary:
var['mykey'] = new_value
eg: var['tej'] = 49.2
There are various commands to perform the operations on the dictionary
.Clear() -- Removes all the entries from the dictionary
.Copy() -- Returns a copy of dictionary
.fromkeys() --Returns a dictionary with specified keys
.get() -- Returns the value of a dictionary entry for a specified key, with an optional fallback value.
.items() -- Returns a list of tuples for each key-value pair in a dictionary.
.keys() -- Returns a list of keys for a dictionary.
.pop() -- Returns the value of a specified key, then removes the key-value pair from a dictionary.
.popitem() -- Returns the last inserted key-value pair from a dictionary as a tuple, and removes the entry.
.setdefault() -- Returns the value of a specified key. If the key does not exist, it is inserted with the specified value.
.update() -- Adds the entries in a specified dictionary, or iterable of key-value pairs, to a dictionary.
.values() -- Returns a view of values for a dictionary.
Comments
Post a Comment