Thursday, 4 April 2024

Python Dictionaries

 

Dictionaries


Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.


In Python, dictionaries are defined within braces {} with each item being a pair in the form key: value. Key and value can be of any type.


Program:

data = {'OS':'Fedora', 'RAM':'Delight', 'CPU':'Dell'}

print(data)

months = {'jan':'31', 'Feb':'28', 'Mar':'31'}

print(months)

# Scripts Ends 

Output:

{'OS': 'Fedora', 'RAM': 'Delight', 'CPU': 'Dell'}

{'jan': '31', 'Feb': '28', 'Mar': '31'}


In this Example OS,RAM,CPU are Key, Fedora,Delight Dell are Values

 

1. Accessing a Value

To access a value, you mention the key in square brackets.

Program:

data = {'OS':'Fedora', 'RAM':'Delight', 'CPU':'Dell'}

print(data['CPU'])

# Scripts Ends 

Output:

Dell


2. Reassigning Elements

You can reassign a value to a key.

Program:

data = {'OS':'Fedora', 'RAM':'Delight', 'CPU':'Dell'}

data['RAM']='Kingston'

print(data)

# Scripts Ends 

Output:

{'OS': 'Fedora', 'RAM': 'Kingston', 'CPU': 'Dell'}



Difference between List, Tuples and dictionary       

                     


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts