Dictionaries in Python Day 1
Dictionaries in Python Day 1
Python dictionary represents a mapping between a key and a value. In simple terms, a Python
dictionary can store pairs of keys and values. Each key is linked to a specific value. Once stored in a
dictionary, you can later obtain the value using just the key.
Characteristics of dictionaries
Unordered: The items in dictionaries are stored without any index value, which is typically a
range of numbers. They are stored as Key-Value pairs, and the keys are their index, which will not
be in any sequence.
Unique: As mentioned above, each value has a Key; the Keys in Dictionaries should be unique. If
we store any value with a Key that already exists, then the most recent value will replace the old
value.
Mutable: The dictionaries are collections that are changeable, which implies that we can add or
remove items after the creation.
AD
Creating a dictionary
There are following three ways to create a dictionary.
Using curly brackets: The dictionaries are created by enclosing the comma-separated Key:
Value pairs inside the {} curly brackets. The colon ‘: ‘ is used to separate the key and value in a
pair.
Using dict() constructor: Create a dictionary by passing the comma-separated key: value
pairs inside the dict().
Using sequence having each item as a pair (key-value)
AD
Example:
Run
AD
Empty Dictionary
When we create a dictionary without any elements inside the curly brackets then it will be an empty
dictionary.
emptydict = {}
print(type(emptydict))
# Output class 'dict'
Run
Note:
A dictionary value can be of any type, and duplicates are allowed in that.
Keys in the dictionary must be unique and of immutable types like string, numbers, or tuples.
AD
1. Retrieve value using the key name inside the [] square brackets
2. Retrieve value by passing key name as a parameter to the get() method of a dictionary.
Example
Run
AD
As we can see in the output, we retrieved the value ‘Jessa’ using key ‘name” and value 1178 using its
Key ‘telephone’.
Method Description
values(
Returns the list of all values present in the dictionary
)
Returns all the items present in the dictionary. Each item will be
items()
inside a tuple as a key-value pair.
AD
We can assign each method’s output to a separate variable and use that for further computations if
required.
Example