Python Dictionary

Table of Contents
< All Topics
Print

Python Dictionary

  • A python dictionary is a group ofkey-value pairs, where the values can be any Python object.
  • The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers.
  • Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
  • The data (or an python object) is stored as key-value pairs using a Python dictionary, where:
    • 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.

How to create a Python Dictionary?

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” }

Example-1

emp = {"Name": "Mohan", "Age": 22, "salary":230000,"Company":"Wipro"}
print(type(emp))

print("printing values:\n ")
print(emp)
#output:

printing values:
 
{'Name': 'Mohan', 'Age': 22, 'salary': 230000, 'Company': 'Wipro'}

How to Create an empty Dictionary?

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 thedict()Constructor: Call thedict()function without any arguments.

# Exaple: Using Curly Braces

Dct = {}      
 
print("Empty Dictionary: ")       
print(Dct)
print(type(Dct))
#Output:

Empty Dictionary: 
{}
# Example: Using the dict() Constructor

Dct = dict()

rint("Empty Dictionary: ")       
print(Dct)
print(type(Dct))
#Output:

Empty Dictionary: 
{}

How to Create a Dictionary using dict() method?

To create a dictionary using thedict()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. Usingzip(): Combine two lists (one for keys and one for values) usingzip().

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 thedict()method to merge two python dictionaries, but it’s not the most common approach. Instead, you typically use methods like theupdate()method or the merge operator (|) introduced in Python 3.9.

Here are some ways to merge dictionaries:

1. Using update() function:

#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'}

2. Using the merge operator (|)(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'}

3. Using unpacking:

#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'}

How to create a Python dictionary with each item as a Pair?

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'}

What is a way to access the values of a Python dictionary?

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:
 

{'Name': 'Parth', 'Age': 20, 'salary': 500000, 'Company': 'Flipkart'}
Employee data :

Name : Parth
Age  : 20
Salary : 50000
Company : Flipkart

Discuss various ways to add values to a dictionary using simple examples.

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.

a. Creating an Empty Dictionary

# 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: 
{}

b. Adding elements to dictionary one at a time

# 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'}

c. Adding set of values with to single Key

# 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')}

How to update a dictionary data?

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')}

a. Deleting values by using del keyword

# 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:

 

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

b. Deleting values using pop() method

# 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

Define ways to iterate dictionary, use simple examples in support

a. Using for loop to print all the keys of a dictionary
b. Using for loop to print all the values of the dictionary

a. Using for loop to print all the keys of a 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)
 

Name
Age
salary
Company

b. Using for loop to print all the values of the dictionary

# 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

c. Using for loop to print the values of the dictionary by using values() method.

## 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

d. Using for loop to print the items of the dictionary by using items() method

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')

Can we pass multiple values for a same key, multiple times?

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'

Define following dictionary functions with suitable examples

The len() function

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() function

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

– 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

The sorted() method:

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.

sort on the basis of keys print("sorted by values: list is:",sorted(dct.values()))#---> sort on the basis of values " style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button">
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']

The clear() method

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'}
{}

The copy() method

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'}

The pop() method

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'}

The popitem() method

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'}

The keys() method

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:

dict_keys([7, 5, 8, 1])

The items() method

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')])

The get() method

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'}

The update() method

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'}

The values() method

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'])

Recommended readings

  1. Visit the official python document related to Python Data structures
  2. Visit the official python document related to Python Dictionary
  3. Easy Learning, Python Strings QAs for Beginner’s to Pro Part-1
  4. Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2
  5. Easy Learning, Python String Functions QAs for Beginner to Pro Part-3

Leave a comment