Python Dictionaries
Dictionary
Data values are stored in key : value pairs using dictionaries.
A dictionary is an ordered collection that can be changed and it will not support duplicate key-values.
Dictionaries are ordered with Python version 3.7. Dictionaries are not ordered in Python 3.6 and earlier.
Curly brackets {}
are used to create dictionaries.
Example :- A simple dictionary
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
print(mydict)
Output :-
Dictionary Items
Dictionary items are ordered, modifiable and don't allow duplicates.
In key : value pairs the dictionary items will be presented and can be referred to by the key name.
Example :- Print the dictionary's 'salary' value :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
print(mydict["salary"])
Output :-
Ordered or Unordered?
Dictionaries are ordered as of Python version 3.7. Dictionaries are unordered in Python 3.6 and earlier.
If we say the ordering of dictionaries, it means that there is a definition of the commands, and that order won't change.
Unordered means that you cannot refer to an item by using an index without a defined order.
Changable
The dictionaries can be modified so that after the dictionary is created we may change, add or remove items.
Duplicates Not Allowed
Dictionaries cannot have the same key for two items. If same key found, existing values overwrite the duplicate values
Example :- A simple dictionary with duplicate key "salary" :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500,
"salary": 3500
}
print(mydict)
Output :-
Dictionary Length
Use the len()
function to find out the number of items in a dictionary.
Example :- Print the dictionary's number of items :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
print(len(mydict))
Output :-
Related Links
Check if Key Exists
For example, you may use the in
keyword to find out whether a given key is in a dictionary :
Example :- Look in the dictionary to see if "id" is present :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
if "id" in mydict:
print("Yes, 'id' is one of the keys in the mydict dictionary")
Output :-
Dictionary Items - Data Types
Dictionary items can have values of all types of data :
Example :- List of dictionaries with strings, int, booleans, and lists datatypes :
mydict = {
"id": 101,
"name": "xy",
"salary": 2500.56,
"married": True,
"dept": ["sales", "service", "accounts"]
}
print(mydict)
Output :-
type()
Dictionaries are defined from a Python perspective like objects with the 'dict' data type:
Example :- Print the data type of a dictionary :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
print(type(mydict))
Output :-
Python - Access Dictionary Items
There are two to access a dictionary items in python, which is
[]
:- Get a dictionary content by refferring to the key name in the square brackets.get()
:- This method is used to get content of a dictionary by providing key name in the method argument.
Accessing Items
Using square brackets, you can retrieve a dictionary's contents by referring to the key name
within the brackets and also you can use a method named get()
, which returns the same result.
Example 1 :- Retrieve the value of the "id" key :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
x = mydict["id"]
y = mydict.get("id")
print(x)
print(y)
Output :-
101
Get Keys and Values
The keys()
method is used to return all key names from a dictionary.
The values()
method is used to return all key values from a dictionary.
Example :- Get all keys and values from a dictionary:
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
x = mydict.keys()
y = mydict.values();
print(x)
print(y)
Output :-
dict_values(['101', 'Suresh', 2500])
Related Links
Get Items
The items()
method returns each item in a dictionary as a list of tuples.
Example 1 :- Get a list of the key:value pairs :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
x = mydict.items()
print(x)
Output :-
Python - Change Dictionary Items
Python provide facilities to change a item value in a dictionary.
Change Values
A specific item's value can be changed by referring to its key name :
Example :- Change the "name" to "Babu" :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict["name"] = "Babu"
print(mydict)
Output :-
Update Dictionary
The dictionary will be updated with the elements from the supplied input using the update()
method.
A dictionary or an iterable object containing key:value pairs must be used as an argument to the function.
Example :- The update()
method can be used to update the "salary" of the employee :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict.update({"salary": 5000})
print(mydict)
Output :-
Python - Add Dictionary Items
Adding Items
Each entry in the dictionary is added using an index key that has a value assigned to the new item.
Example :- Adding a new key "dept" :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict["dept"] = "sales"
print(mydict)
Output :-
Update Dictionary
The update()
method updates the dictionary with items from a provided input. If the item does not already exist, it will be added to the system.
A dictionary or an iterable object with key:value pairs must be used as the argument to the function
Example :- The update()
method can be used to add a dept item to the dictionary :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict.update({"dept": "sales"})
print(mydict)
Output :-
Python - Remove Dictionary Items
Remove things from a dictionary can be done in a variety of ways :
The pop()
method and del
keyword are used to delete an item from a dictionary.
Example 1 :- Removes an item using pop()
method and del
keyword :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict.pop("name")
print(mydict)
del mydict["salary"]
print(mydict)
Output :-
{'id': '101'}
The clear()
method is used to delete all items from a dictionary and make it empty dictionary.
Example 2 :- Using the clear()
method, the dictionary is emptied of all items :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict.clear()
print(mydict)
Output :-
The del
keyword is used to delete all items in a dictionary and also delete the dictionary itself.
Example 3 :- The del
keyword can also be used to remove the entire dictionary :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
del mydict
print(mydict) #this will cause an error because "mydict" no longer exists.
Output :-
File "demo_dictionary_del3.py", line 7, in < module>
print(mydict) #this will cause an error because "mydict" no longer exists.
NameError: name 'mydict' is not defined
Python - Loop Dictionaries
Using a for
loop, you may loop through a dictionary.
In a dictionary looping through, the return value is the dictionary keys, but there are several methods to return the dictionary's actual values.
Example 1 :- Print out the dictionary's key names one by one :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
for x in mydict:
print(x)
Output :-
name
salary
Example 2 :- Print all dictionary values one by one :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
for x in mydict:
print(mydict[x])
Output :-
Suresh
2500
Example 3 :- Use the items()
method to loop through both keys and values :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
for x, y in mydict.items():
print(x, " = ", y)
Output :-
name = Suresh
salary = 2500
Python - Copy Dictionaries
By entering dict2 = dict1
, you will just be copying the dictionary's contents, and any modifications made to dict1
will immediately be made to dict2
.
Making a copy can be done in several ways, including by using the built-in dictionary method copy()
and dict()
.
Example :- make a copy of a dictionary's contents using copy()
and dict()
methods :
mydict = {
"id": "101",
"name": "Suresh",
"salary": 2500
}
mydict2 = mydict.copy()
mydict3 = dict(mydict)
print(mydict2)
print(mydict3)
Output :-
{'id': '101', 'name': 'Suresh', 'salary': 2500}
Nested Dictionaries
When a dictionary contains another dictionary, this is called nesting dictionary.
Exmaple 1 :- A dictionary that contains three dictionaries should be constructed :
employees = {
"emp1" : {
"name" : "aa",
"year" : 2004
},
"emp2" : {
"name" : "bb",
"year" : 2007
},
"emp3" : {
"name" : "cc",
"year" : 2011
}
}
print(employees)
Output :-
If you wish to combine three dictionaries into one, For example.
Example 2 :- Construct two dictionaries, then create a dictionary that contains the other two dictionaries :
emp1 = {
"name" : "aa",
"year" : 2004
}
emp2 = {
"name" : "bb",
"year" : 2007
}
employees = {
"emp1" : emp1,
"emp2" : emp2
}
print(employees)
Output :-