As on of the way use Curly brackets {} to generate a Python dictionary.
With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:).
Another way to define a dictionary is by dict() method
Syntax:
Dct={“key1″:”value1” , “key2″:”value2” , ….., “keyN”:”valueN” }
emp = {"Name": "Mohan", "Age": 22, "salary":230000,"Company":"Wipro"}
print(type(emp))
print("printing values:\n ")
print(emp)
#output:
<class 'dict'>
printing values:
{'Name': 'Mohan', 'Age': 22, 'salary': 230000, 'Company': 'Wipro'}
To create an empty dictionary in Python, you can use one of the following methods:
1. Using Curly Braces: Assign an empty pair of curly braces to a variable.
2. Using the dict()
Constructor: Call the dict()
function without any arguments.
# Exaple: Using Curly Braces
Dct = {}
print("Empty Dictionary: ")
print(Dct)
print(type(Dct))
#Output:
Empty Dictionary:
{}
<class 'dict'>
# Example: Using the dict() Constructor
Dct = dict()
rint("Empty Dictionary: ")
print(Dct)
print(type(Dct))
#Output:
Empty Dictionary:
{}
<class 'dict'>
To create a dictionary using the dict()
method in Python, you can utilize various approaches:
1. Using Keyword Arguments: You can pass key-value pairs directly as keyword arguments.
2. From a List of Tuples: You can create a dictionary from a list of tuples, where each tuple contains a key-value pair.
3. Using zip()
: Combine two lists (one for keys and one for values) using zip()
.
4. From Another Dictionary: You can create a new dictionary by passing an existing dictionary.
# Example-1: Using Keyword Arguments
Dct = dict({ 1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
## NOTE: here key is of interger type and value are of string type
print(Dct)
#Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
# Example-2: From a List of Tuples:
Dct = dict([('First', 'HCL'), ('Second', 'Wipro'), ('Third', 'Infosys')])
print(Dct)
#Output:
{'First': 'HCL', 'Second': 'Wipro', 'Third': 'Infosys'}
# Example-3: Using zip()
keys = ['a', 'b', 'c']
values = [1, 2, 3]
# Using zip() and dict() to create a python dictionary
result_dict = dict(zip(keys, values))
print(result_dict)
#Output:
{'a': 1, 'b': 2, 'c': 3}
# Example-4 : From Another Python Dictionary
re_dict = {'key1': 'value1'}
new_dict = dict(re_dict)
print(new_dict)
#Output:
{'key1': 'value1'}
Yes, you can use the dict()
method to merge two python dictionaries, but it’s not the most common approach. Instead, you typically use methods like the update()
method or the merge operator (|
) introduced in Python 3.9.
Here are some ways to merge dictionaries:
#Example:
dict1 = {'a': "Python", 'b': "is"}
dict2 = {'b': " a good", 'c': " programming language"}
dict1.update(dict2)
#Output:
{'a': 'Python', 'b': ' a good', 'c': ' programming language'}
|
) (Python 3.9+):#Example: Using merge operator
dict1 = {'a': "Python", 'b': "is"}
dict2 = {'b': " a good", 'c': " programming language"}
merged_dict = dict1 | dict2
print(merged_dict)
#Output:
{'a': 'Python', 'b': ' a good', 'c': ' programming language'}
#Example
dict1 = {'a': "Python", 'b': "is"}
dict2 = {'b': " a good", 'c': " programming language"}
merged_dict = {**dict1, **dict2}
print(merged_dict)
#Output:
{'a': 'Python', 'b': ' a good', 'c': ' programming language'}
To create a python dictionary with the help of pair of elements, one can prepare a separate tuple having individual pairs in it. Then place all such tuples inside a list. this means that prepare a dictionary with the help of list of tuples. Let us have a simple example of this as under:
# Example: Dictionary with each item as a Pair -> dictionary of list of tuples
Dict = dict([(4, 'Abul Kalam'), (2, 'C.N. Rao')]) # <--- dictionary of list of tuples
print("\nDictionary with each item as a pair: ")
print(Dict)
#Opuput:
Dictionary with each item as a pair:
{4: 'Abul Kalam', 2: 'C.N. Rao'}
To access the values in a Python dictionary, you can use the key in an array-index-like approach. For example, if you have a dictionary named emp that contains a mapping of names, ages, salary and company. you can retrieve the individual key (say age) of a specific person by referencing their name as the key. Here’s how you can do it:
#Example: Access python dictionary values
emp = {"Name": "Parth", "Age": 20, "salary":500000,"Company":"Flipkart"}
print(type(emp),"\n")
print(emp)
print("Employee data :\n")
print("Name : %s" %emp["Name"])
print("Age : %d" %emp["Age"])
print("Salary : %d" %emp["salary"])
print("Company : %s" %emp["Company"])
#Output:
<class 'dict'>
{'Name': 'Parth', 'Age': 20, 'salary': 500000, 'Company': 'Flipkart'}
Employee data :
Name : Parth
Age : 20
Salary : 50000
Company : Flipkart
Creating an empty dictionary in Python is straightforward and can be done using curly braces {
}
or the dict()
constructor. Below is a detailed explanation of your code snippets, along with additional self-explanatory examples.
a. Creating an empty Dictionary.
b. Adding elements to dictionary one at a time.
c. Adding set of values with to single Key.
# Example: a. Creating an Empty Dictionary
Dct = {} # This initializes an empty dictionary
# Here, Dct is assigned an empty dictionary.
# The {} syntax indicates that there are no key-value pairs in the dictionary at this point.
print("Empty Dictionary: ")
print(Dct)
#Output:
Empty Dictionary:
{}
# Adding elements to dictionary one at a time to an empty python directory
Dct = {}
Dct[0] = 'Python'
Dct[2] = 'is'
Dct[3] = ' a Programming'
Dct[4]= 'Language'
print(Dct)
#Output:
{0: 'Python', 2: 'is', 3: ' a Programming', 4: 'Language'}
# Adding set of values
# with a single Key
# The key named lib doesn't exist to dictionaryy
Dct['Lib'] = 'Pandas','NumPy','Matplotlib','SciPy','GGplot','TensorFlow'
print("\n Updated Python Dictionary will be: ")
print(Dct)
#Output:
Updated Python Dictionary will be:
{0: 'Python', 2: 'is', 3: ' a Programming', 4: 'Language', 'Lib': ('Pandas', 'NumPy', 'Matplotlib', 'SciPy', 'GGplot', 'TensorFlow')}
An existing value can also be updated using the update() method.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, it will create a new key value pair.
# Updating existing Key's Value
Dct[3] = 'an OOPs based Programming'
print("\nUpdated key value: ")
print(Dct)
#Output:
Updated key value:
{0: 'Python', 2: 'is', 3: 'an OOPs based Programming', 4: 'Language', 'Lib': ('Pandas', 'NumPy', 'MatplotLib', 'SciPy', 'GGplot', 'TensorFlow')}
# Example: By using del keyword
emp = {"Name": "Parth", "Age": 20, "salary":50000,"Company":"Flipkart"}
print(type(emp),"\n")
print("Deleting some of the employee data")
del emp["Name"]
del emp["Company"]
print("\nprinting the modified information ")
print(emp)
print("\nDeleting the dictionary: emp");
del emp
print("\nLets try to print it again ");
try:
print(emp)
except Exception as e:
print(e)
#Output:
<class 'dict'>
Deleting some of the employee data
printing the modified information
{'Age': 20, 'salary': 50000}
Deleting the dictionary: emp
Lets try to print it again
name 'emp' is not defined
# Creating a Dictionary
Dct1 = {1: 'EzyLearning', 2: 'Tech-Learning', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dct1.pop(2)
print(Dct1)
print(pop_key)
#output:
{1: 'EzyLearning', 3: 'Website'}
Tech-Learning
a. Using for loop to print all the keys of a dictionary
b. Using for loop to print all the values of the dictionary
## Example-1 for loop to print all the keys of a dictionary
emp = {"Name": "Parth", "Age": 20, "salary":50000,"Company":"Flipkart"}
print(type(emp),"\n")
for x in emp:
print(x)
<class 'dict'>
Name
Age
salary
Company
# Example-2 : for loop to print all the values of the dictionary
emp = {"Name": "Parth", "Age": 20, "salary":500000,"Company":"Flipkart"}
for x in emp:
print(emp[x])
Parth
20
500000
Flipkart
## Example-3: for loop to print the values of the dictionary by using values() method.
emp = {"Name": "Parth", "Age": 20, "salary":50000,"Company":"Flipkart"}
for x in emp.values():
print(x)
Parth
20
50000
Flipkart
Example-4: for loop to print the items of the dictionary by using items() method
emp = {"Name": "Parth", "Age": 20, "salary":500000,"Company":"Flipkart"}
for x in emp.items():
print(x)
('Name', 'Parth')
('Age', 20)
('salary', 50000)
('Company', 'Flipkart')
In the dictionary, we cannot store multiple values for the same keys.
If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
try:
Employee = {"Name": "Parthsarthi", "Age": 22, "salary":45000, "Company":"WIPRO", (100,201,301):"Department ID"}
for x,y in Employee.items():
print(x,y)
except Exception as e:
print(e)
Name Parthsarthi
Age 22
salary 45000
Company WIPRO
(100, 201, 301) Department ID
try:
Employee = {"Name": "Parthsarthi", "Age": 22, "salary":45000, "Company":"WIPRO", [100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
except Exception as e:
print(e)
unshushable type: 'list'
Gives the length of key : value pairs. This function allows for an efficient way to determine how many entries exist within a dictionary or similar data structure. By iterating through each key and its associated value, we can tally the total count. This can be particularly useful for validating data integrity or assessing the size of datasets in applications. The output provides a straightforward numerical representation, making it easy to understand and utilize in further computations or logic.
emp = {"Name": "Parth", "Age": 20, "salary":500000,"Company":"Flipkart"}
print(len(emp))
#Output:
4
The all()
method in Python is used to check if all elements in an iterable (such as a list, tuple, or dictionary) evaluate to True
.
When used with a dictionary, the all()
method checks if all keys or values in the dictionary evaluate to True
.
# Example
my_dict = {'a': 10, 'b': True, 'c': 'Hello', 'd': [1,,3]}
# Verify that all values in the dictionary are True
result = all(my_dict.values())
print(result) # Output: True
#Output:
True
– The any()
method in Python is used to check if at least one element in an iterable (such as a list, tuple, or dictionary) evaluates to True
.
# Example dictionary
my_dict = {'a': 0, 'b': False, 'c': None, 'd': 10+45}
# Check if any value in the dictionary is True
result = any(my_dict.values())
print(result) # Output: True
#### Here the `any()` method checks if any of the values in the `my_dict` dictionary evaluate to `True`.
#### Since the key 'd' has a value of 10, which is a truthy value, the result is `True`.
#Output:
True
Just 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. Here is a simple example to show the use of the function.
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai"}
print("original list: ",dct)
print("sorted by keys: list is:",sorted(dct.keys()) ) #---> sort on the basis of keys
print("sorted by values: list is:",sorted(dct.values()))#---> sort on the basis of values
#Output:
original list: {7: 'Ajai', 5: 'Vijay', 8: 'Sujai', 1: 'Sanjai'}
sorted by keys: list will be: [1, 5, 7, 8]
sorted by values: list will be: ['Ajai', 'Sanjai', 'Sujai', 'Vijay']
It is mainly used to delete all the items of the dictionary.
# dictionary methods
dct = {1: "Snapdeal", 2: "Rediff Shopping", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
print(dct)
# clear() method
dct.clear()
print(dct)
#Output:
{1: 'Snapdeal', 2: 'Rediff Shopping', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
{}
It returns a copy of the dictionary which is created previously.
# dictionary methods
dct = {1: "Sanpdeal", 2: "Rediff Shopping", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
print(dct)
# copy() method
dct_copy = dct.copy()
print(dct_copy)
# original and copy will have saprate memory spaces.
#Output:
{1: 'Snapdeal', 2: 'Rediff Shopping', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
{1: 'Snapdeal', 2: 'Rediff Shopping', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
It mainly eliminates the element using the defined key.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai"}
# pop() method
x = dct.pop(5)
print(x)
print(dct)
#Output:
Vijay
{7: 'Ajai', 8: 'Sujai', 1: 'Sanjai'}
It removes the most recent key-value pair entered
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai"}
# popitem() method
x = dct.popitem()
print(x)
x = dct.popitem()
print(x)
print(" Updated dctionary :")
print(dct)
#Output:
(1, 'Sanjai')
(8, 'Sujai')
Updated dctionary :
{7: 'Ajai', 5: 'Vijay'}
It returns all the keys of the dictionary.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai"}
# keys() method
x = dct.keys()
print(type(x))
print(x)
#Output:
<class 'dict_keys'>
dict_keys([7, 5, 8, 1])
It returns all the key-value pairs as a tuple.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai"}
# items() method
x = dct.items()
print(x)
#Output:
dict_items([(7, 'Ajai'), (5, 'Vijay'), (8, 'Sujai'), (1, 'Sanjai')])
It is used to get the value specified for the passed key.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai", 2:"Dhananjai"}
# get() method
x = dct.get(8)
print(x)
x = dct.get(2)
print(x)
print(dct)
#Output:
Sujai
Dhananjai
{7: 'Ajai', 5: 'Vijay', 8: 'Sujai', 1: 'Sanjai', 2: 'Dhananjai'}
It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai", 2:"Dhananjai"}
# update() method
dct.update({3:'Jai'})
print(dct)
#Output:
{7: 'Ajai', 5: 'Vijay', 8: 'Sujai', 1: 'Sanjai', 2: 'Dhananjai', 3: 'Jai'}
It returns all the values of the dictionary with respect to given input.
# dictionary methods
dct = {7: "Ajai", 5: "Vijay", 8: "Sujai", 1: "Sanjai", 2:"Dhananjai"}
# values() method
x=dct.values()
print(x)
#Output:
dict_values(['Ajai', 'Vijay', 'Sujai', 'Sanjai', 'Dhananjai'])
All about java servlets Part-2 What is a website? Website is a collection of related…
Let's train the machine. Machine learning is a growing technology which enables computers to learn…
“Unless you try to do something beyond what you have already mastered, you will never…
Whenever you decide to start coding and you want to become budding coder or programmer…
C components are essential elements of a C program, including comments, preprocessor directives, functions, statements,…
All about java servlets Part-2 What is a website? Website is a collection of related…