Dictionary in Python
Dictionary in Python
Topperworld.in
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.
• Dictionary in Python is a collection of keys values, used to store data values
like a map, which, unlike other data types which hold only a single value as
an element.
❖ Creating a 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:
✓ In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.
• Python provides the built-in function dict() method which is also used to
create the dictionary.
©Topperworld
Python Programming
Example:
# Creating a Dictionary
Dict = {1: 'TopperWorld', 'name': 'For', 3: 'TopperWorld'}
Output:
Accessing a element using key:
For
Accessing a element using key:
TopperWorld
©Topperworld
Python Programming
Note: The value is updated if the key-value pair is already present in the
dictionary. Otherwise, the dictionary's newly added keys.
Example:
Output:
©Topperworld
Python Programming
❖ Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example:
Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
©Topperworld
Python Programming
❖ Dictionary Methods
Method Description
©Topperworld
Python Programming
Example:
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "Wonderland"
}
Output:
Name: Alice
Age: 30
City: Wonderland
©Topperworld