Dictionaries are used to store data in Key : Value pairs.
A dictionary is a collection which is ordered (from Python version > =3.7), changeable, and does not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Dictionary items are presented in Key : Value pairs, and can be referred to by using the key name.
emp_details = {
"name" : "Sameer"
"EmpID" : "AECS***"
"Designation" : "Vice President"
}
print(emp_details)
create an empty dictionary:
my_dict= {}
The dict() constructor builds dictionaries directly from sequences of key-value pairs.
>>> dict([('fname','Rajeev'), ('lname','Suman'), ('hobby','Dancing')])
dict comprehensions can be used to create dictionaries from arbitrary key and value expressions.
>>> {x: x**2 for x in (1, 2, 3)}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments.
>>> dict(fname='Rajeev', lname='Suman', hobby='Dancing')
Dictionaries Properties :
- Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. Unordered means that the items does not have a defined order and we cannot refer to an item by using an index.
- Changeable
Dictionary items are changeable, meaning that we can change, add, and remove items in a Dictionary after it has been created.
- Duplicates Not Allowed
A Dictionary cannot have two items with the same key. Duplicate values will overwrite existing values.
Dictionary Length
len() function is use to determine the length of a Dictionary.
my_dict= {
"Name": "Sameer",
"Age": 31,
"Sex": "Male",
"isMerried":False,
"Designation" : "Vice President"
}
print(len(my_dict))
Accessing Dictionaries items:
To access the items of a dictionary we use its key name, inside square brackets.
By using get(key) we can also get the same result.
emp_name = my_dict["Name"]
emp_name = my_dict.get("Name")
Get Keys:
The keys() method will return a list of all the keys in the dictionary.
emp_records = my_dict.keys()
Get Values:
The values() method will return a list of all the values in the dictionary.
emp_records = my_dict.values()
Get Items:
The items() method will return each item in a dictionary, as tuples in a list.
emp_records = my_dict.items()
Check if Key Exists:
The in keyword helps us to determine if a specific key is present in a dictionary or not.
if "name" in my_dict:
print(my_dict[name]);
Change Dictionary Items
Change the value of a specific item, by refering to to its key name.
my_dict["age"] = 29
Update Dictionary
The update() method will update the dictionary with the items from the given argument. If the item does not exist, the item will be added. The argument must be a dictionary, or an iterable object with key:value pairs.
my_dict.update({"name":"Ruchit"})
Add Items to Dictionary
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
my_dict["hobby"] = "Reading"
Remove Specified Items
The pop() method removes the item with the specified key name.
my_dict.pop("age")
The popitem() method removes the last inserted item.for versions before 3.7, a random item is removed instead):
my_dict.popitem()
The del keyword also removes the element from specified key name. The del keyword can also delete the dictionary completely:
del my_dict["hobby"]
del my_dict
Clear the Dictionary
The clear() method empties the Dictionaries. The Dictionaries still remains, but it has no content.
my_dict.clear()
print(my_dict)
Loop Through a Dictionary
- using for loop:
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
for x in my_dict: print(x) // print all key names in the dictionary one by one. print(my_dict[x]) //print all value in the dictionary one by one.
- We can also use the values() method to return values of a dictionary.
for x in my_dict.values(): print(x)
- We can also use the keys() method to return keys of a dictionary.
for x in my_dict.keys(): print(x)
- We can also loop through both keys and values using the items() method.
for x, y in my_dict.items(): print(x,y)
Copy Dictionarys
We cannot copy a Dictionaries simply by using assignment operator as Dictionaries2 = Dictionaries1, because: Dictionaries2 will only be a reference to Dictionaries1, and changes made in Dictionaries1 will automatically also be made in Dictionaries2. We can use following ways to copy a Dictionaries:
- using built-in copy() method.
my_dict2 = my_dict.copy() print(my_dict2)
- using built-in dict() method.
my_dict2 = dict(my_dict) print(my_dict2)