What is Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
- This data structure is mutable
- The components of dictionary were made using keys and values.
- Keys must only have one component.
- Values can be of any type, including integer, list, and tuple.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:-
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object.
Accessing the dictionary values
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Adding Dictionary Values
Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
print("Empty Dictionary: ")
print(Dict)
Adding elements to dictionary one at a time
Dict = {}
Dict[0] = 'Peter'
Dict[1] = 'Joseph'
Dict[2] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[0] = 'Peter'
Dict[1] = 'Joseph'
Dict[2] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Adding set of values with a single Key The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
print("\nDictionary after adding 3 elements: ")
print(Dict)
Updating existing Key's Value
Dict = {}Dict[0] = 'Peter'
Dict[1] = 'Joseph'
Dict[2] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'MK Tutorial'
print("\nUpdated key value: ")
print(Dict)
print("\nUpdated key value: ")
print(Dict)
How to take input in Dictionary
Employee={}
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Deleting Elements using del Keyword
Employee={}
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Deleting Elements using pop() Method
Dict1 = {1: 'MK Tutorial', 2: 'Educational', 3: 'Website'}
pop_key = Dict1.pop(2)
print(Dict1)
pop_key = Dict1.pop(2)
print(Dict1)
Iterating Dictionary
for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
for x in Employee:
print(x)
for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(Employee[x])
for x in Employee:
print(Employee[x])
for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.values():
print(x)
for x in Employee.values():
print(x)
for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.items():
print(x)
for x in Employee.items():
print(x)
Built-in Dictionary Functions
Method | Description |
---|---|
len() | The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each key-value pair. Example:- dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"} print(len(dict)) it returns 4 |
sorted() | Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary's keys. The ascending sorting has no effect on the original Python dictionary. Example:- dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"} print(sorted(dict)) it returns [ 1, 5, 7, 8] |
clear() | It is mainly used to delete all the items of the dictionary. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} dict.clear() print(dict) it returns { } |
copy() | It returns a shallow copy of the dictionary which is created. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} dict_demo = dict.copy() print(dict_demo) it returns {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'} |
pop() | It mainly eliminates the element using the defined key. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} dict_demo = dict.copy() x = dict_demo.pop(1) print(x) it returns {2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'} |
popitem() | removes the most recent key-value pair entered Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} dict_demo.popitem() print(dict_demo) it returns {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'} |
keys() | It returns all the keys of the dictionary. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} print(dict_demo.keys()) it returns dict_keys([1, 2, 3, 4, 5]) |
items() | It returns all the key-value pairs as a tuple. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} print(dict_demo.items()) it returns dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')]) |
get() | It is used to get the value specified for the passed key. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} print(dict_demo.get(3)) it returns Facebook |
update() | It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} dict_demo.update({3: "TCS"}) print(dict_demo) it returns {1: 'Hcl', 2: 'WIPRO', 3: 'TCS'} |
values() | It returns all the values of the dictionary with respect to given input. Example:- dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"} print(dict_demo.values()) it returns dict_values(['Hcl', 'WIPRO', 'TCS']) |