Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
Keys must be an immutable element.
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
A Dictionary is enclosed under curly braces {}. For Example:
We can also separate keys and values from with the help of this code.
In [22]:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for k,v in employee.items(): #k holds keys and v holds values.
print(f'{k} holds {v}')
name holds Abhi
role holds Trainer
course holds data science
duration holds 3
How to create dictionary with user inputs:¶
To create a dictionary with user inputs , we may ask keys and values from user and add them in an empty dictionary. For Example:
In [23]:
mydict = {}
for i in range(5):
k = input("Enter Key : ")
v = input("Enter Values : ")
mydict[k] = v
print(mydict)
Enter Key : name
Enter Values : abhi
Enter Key : role
Enter Values : trainer
Enter Key : course
Enter Values : data science
Enter Key : duration
Enter Values : 3
Enter Key : projects
Enter Values : 50
{'name': 'abhi', 'role': 'trainer', 'course': 'data science', 'duration': '3', 'projects': '50'}
how to add an iterables items in a dictionaries: update()¶
update() method adds items (key value pair) from an iterable in a dictionary. For Example:
You can also update items from list or tuple or sets in a dictionary. But the only condition is it should be in key value form. A simple list cannot be converted in a dictionary. For Example :
Now , above list is in form of key value pair. if we want to convert list items in a dictionary , our list should have tuples as list items with key value pair in it. For Example:
In above code we have set default value of role is 'not known' . So if role key does not exist in dictionary or is removed. default key value pair will be added in dictionary. For Example.
1.Write a Python script to merge two Python dictionaries
2.Write a Python program to iterate over dictionaries using for loops.
3.Write a Python program to remove a key from a dictionary.
4.Write a Python program to sort a given dictionary by key.
5.Write a Python program to get the maximum and minimum value in a dictionary.
6.Write a Python program to check multiple keys exists in a dictionary.