Python Dictionaries
Dictionaries are a ordered list of data items. Dictionary items are key-value pairs, separated by commas and wrapped in curly brackets {}.
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
print(details)
Output
{'name': 'Rahul', 'age': 22, 'canVote': True}
Access Dictionary Items
To retrieve the value of a dictionary item, place the key within square brackets.
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
print(details["name"])
Output
Rahul
Add Items to a Dictionary
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
details["DOB"]
=
2003
print(details)
Output
{'name': 'Rahul', 'age': 22, 'canVote': True, 'DOB': 2003}
Remove Dictionary Items
There are a few ways to delete items from a dictionary.
pop()
The pop()
function deletes the element with the given key name.
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
details.pop("canVote")
print(details)
Output
{'name': 'Rahul', 'age': 22}
clear()
The clear()
function deletes all the elements from the dictionary.
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
details.clear()
print(details)
Output:
{}
popitem()
The popitem()
function deletes the last item from the dictionary.
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
details.popitem()
print(details)
Output:
{'name': 'Rahul', 'age': 22}
Copy Dictionaries
Example:
details =
{
"name":"Rahul",
"age":22,
"canVote":True
}
newDict = details.copy()
print(newDict)
Output:
{'name': 'Rahul', 'age': 22, 'canVote': True}