Python Dictionary: A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. In Python, Dictionaries are mutable, which means they can be changed. The values that the keys point to can be any Python value. And these are unordered. Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces {}.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } print(thisdict)
Output
{‘brand’: ‘Lamborghini’, ‘model’ : ‘GT’, ‘year’ : 1963 }
Python Dictionary
Accessing Items
You can access the items in the Python dictionary by referring it the key name, inside square brackets. And there is also a method called get() that will also help in accessing the element from a dictionary.
Example
x = thisdict["model"]
Output: Lamborghini
For accessing the elements we can also use the get()
Example
x = thisdict.get("model")
Output: Lamborghini
Change the Values
You can change the value of a specific item by referring to its key name
Example: change the year to 2019
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } thisdict["year"] = 2019
Output
{‘brand’: ‘Lamborghini’, ‘model’: ‘GT’, ‘year’ = 2019}
Looping through Dictionary
You can loop through a dictionary by suing for a loop. The return value is the keys of the dictionary, but there are methods to return the values as well.
Example
for x in thisdict: print(x)
Output
brand
model
year
If you would like to print all the values in the Python dictionary, one by one
Example
for x in thisdict: print(thisdict[x])
Output
Lamborghini
GT
1963
Return Values
You can return the values by using values( )
Example
for x in thisdict.values(): print(x)
Output
Lamborghini
GT
1963
Loop through Dictionary
You can also loop the dictionaries by using the items() function.
Example
for x, y in thisdict.items(): print(x, y)
Output
brand Lamborghini
model GT
year 1963
Checking ‘if’ key exists
You can also check whether a specific key exists in the dictionary.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output
Yes, ‘model’ is one of the keys in the thisdict dictionary
Dictionary Length
To determine how many items a dictionary has (key-value pairs), using len( ) method.
Example
print(len(thisdict))
Output: 3
Adding items to Dictionary
Adding a new item to the dictionary is done by using a new index key and assigning a value to it.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } thisdict["color"] = "red" print(thisdict)
Output
{‘brand’: ‘Lamborghini’, ‘model’: ‘GT’, ‘year’ : 1963, ‘color’ : ‘red’ }
Removing Items
There are several methods to remove items from dictionary. We can use the pop( ). All the items from a dictionary can be deleted at once by using clear() method. And the items in a Nested dictionary can also be deleted by using del keyword and providing specific nested key and a particular key to be deleted from that nested Dictionary.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } thisdict.pop("model") print(thisdict)
Output: {‘brand’: ‘Lamborghini’, ‘year’: 1963}
We can also use the popitem( ) to remove the last inserted item.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } thisdict.popitem( ) print(thisdict)
Output: {‘brand’: ‘Lamborghini’, ‘model’ : ‘GT’ }
We can also use the del keyword for removing the item with the specified key name.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } del thisdict["model"] print(thisdict)
Output: {‘brand’: ‘Lamborghini’, ‘year’: 1963 }
Empties Dictionary
We can use clear( ) to empty the directory.
Example
thisdict = { "brand": "Lamborghini", "model": "GT", "year": 1963 } thisdict.clear( ) print(thisdict)
Output: {}
Dictionary Constructor
We can also use dictionaries by using constructors.
Example
thisdict = dict(brand="Lamborghini", model="GT", year=1963) print(thisdict)
Output:{‘brand’: ‘Lamborghini’, ‘model’: ‘GT’, ‘year’: 1963}
Dictionary Methods
A method, in the context of object-oriented programming, is a procedure or a function in the class. As a part of the class, a method defines the behavior of class instance. A class can have more than one method.
Method | Description |
---|---|
clear( ) | removes all the elements from the dictionary |
copy( ) | Returns a copy of the dictionary |
fromkeys( ) | Returns a dictionary with the specified keys and values |
get( ) | Returns the value of the specified key |
items( ) | Returns a list containing a dictionary for each key-value pair |
keys( ) | Returns a list containing the dictionary’s keys |
pop( ) | Removes the element with the specified key |
popitem( ) | Removes the last inserted key-value pair |
setdefault( ) | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update( ) | Updates the dictionary with the specified key-value pairs |
values( ) | Returns a list of all the values in the dictionary |
Properties of Dictionary Keys
In Python Dictionary values will not be having any restrictions. They can be in either standard objects or user-defined objects. And it is not true for keys.
There are two main points to keep in mind regarding Keys. They are as follows:
1) More than one entry per key is not allowed, i.e. no duplicate key is allowed. If duplicate keys are allowed then last assignment keys will win.
Example
dict = {'Name': 'Safia', 'Age': 27, 'Name': 'Shaik'} print "dict['Name']: ", dict['Name']
Output: dict [‘Name’]: Mani
2) Keys must be immutable, which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed.
Example
dict = {'Name': 'Safia', 'Age': 27, 'Name': 'Shaik'} print "dict['Name']: ", dict['Name']
Output
Traceback (most recent call last):File “test.py”, line 3,
in <module>dict = {[‘Name’]: ‘Zara’, ‘Age’: 7};
Type Error: unhashable type: ‘list’