Table of Contents
Python dictionary data type
- A dictionary is a collection that is unordered, changeable, and indexed in nature.
- The dictionaries are written with curly brackets { }.
- Python dictionaries have keys and values.
Example
Create dictionary
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
print(d)
Output
{ ‘name’: ‘Ravi’, ‘brand’: ‘NIELITBHU’, ‘year’: 2000 }
How to Access dictionary Items
- To access list items by using the keyname, inside square brackets.
Example
Create dictionary
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
c=d["name"]
print(c)
Output
Ravi
get method
- You can also access the dictionary item using the get( ) method/function.
Example
Create dictionary
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
c=d.get("name")
print(c)
Output
Ravi
Check if control statement in dictionary
- Using in keywords to determine if a specified item is present in a dictionary.
Example
Use of control statement in dictionary
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
if 'brand' in d:
print("yes found")
else:
print("Not found")
Output
yes found
How to Change Item Value in dictionary
- In a dictionary to change the value of a specific item by referring to its key name
Example
Use of control statement in dictionary
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
print("before changing")
print(d)
d["year"]=2002
print("After changing")
print(d)
Output
before changing
{‘name’: ‘Ravi’, ‘brand’: ‘NIELITBHU’, ‘year’: 2000}
After changing
{‘name’: ‘Ravi’, ‘brand’: ‘NIELITBHU’, ‘year’: 2002}
{‘name’: ‘Ravi’, ‘brand’: ‘NIELITBHU’, ‘year’: 2000}
After changing
{‘name’: ‘Ravi’, ‘brand’: ‘NIELITBHU’, ‘year’: 2002}
To access dictionary of a member by using for loop.
Example
Use of for loop
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
for x in d:
print(x)
Output
name
brand
year
brand
year
Example
Print all values
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
for x in d:
print(d[x])
Output
Ravi
NIELITBHU
2000
NIELITBHU
2000
Example
values( ) : This function to return values of a dictionary.
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
for x in d.values():
print(x)
Output
Ravi
NIELITBHU
2000
NIELITBHU
2000
Example
items() : This function return both keys and values.
d = { "name": "Ravi",
"brand": "NIELITBHU",
"year": 2000}
for x,y in d.items():
print(x,y)
Output
name Ravi
brand NIELITBHU
year 2000
brand NIELITBHU
year 2000