Dictionaries
Dictionary in Python is a collection of key values, used to store data values like a map, which, unlike other data types which hold only a single value as an element. Dictionary holds the `key:value` pair. Key-Value is provided in the dictionary to make it more optimized. Dictionary is a collection which is ordered and mutable. No duplicate members.
Dict = {1: 'Liberation', 2: 'By', 3: 'Education'}
print(Dict)
{1: 'Liberation', 2: 'By', 3: 'Education'}
Creating a Dictionary: In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by 'comma'. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
Example:
# Creating a Dictionary with Integer Keys
Dict = {1: 'Liberation', 2: 'By', 3: 'Education'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'LiBed', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Liberation', 2: 'By', 3: 'Education'}
Dictionary with the use of Mixed Keys:
{'Name': 'LiBed', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing curly braces {}.
Example:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary with dict() method
Dict = dict({1: 'Liberation', 2: 'By', 3: 'Education'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, 'LIBED'), (2, 'Tutorial')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Liberation', 2: 'By', 3: 'Education'}
Dictionary with each item as a pair:
{1: 'LIBED', 2: 'Tutorial'}
Check if Key Exists: To determine if a specified key is present in a dictionary use the in keyword.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
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, use the len().
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(len(thisdict))
Output:
3
Loop Through a Dictionary: You can loop through a dictionary by using a for loop. When looping through a dictionary, the return values are the keys of the dictionary, but there are methods to return the values as well.
Example:
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
for x in dict1:
print(x)
print(dict1[x])
Output:
1
Python
2
Java
3
Ruby
4
Scala
Example:
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
for x in dict1.keys():
print(x)
for x in dict1.values():
print(x)
for x, y in dict1.items():
print(x, y)
Output:
1
2
3
4
Python
Java
Ruby
Scala
1 Python
2 Java
3 Ruby
4 Scala
Nested Dictionary: Nested Dictionary can be created as shown below.
Example:
# Creating a Nested Dictionary
Dict = {1: 'Python', 2: 'Tutorials', 3: {'A': 'Welcome', 'B': 'To', 'C': 'LIBED'}}
print(Dict)
Output:
{1: 'Python', 2: 'Tutorials', 3: {'A': 'Welcome', 'B': 'To', 'C': 'LIBED'}}
Adding elements to a Dictionary: Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = 'Value'. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary. While adding a value, if the key-value already exists, the value gets updated; otherwise a new Key with the value is added to the Dictionary.
Example:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'LIBED'
Dict[2] = 'PYTHON'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'Hello', '2': 'World'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'LIBED', 2: 'PYTHON', 3: 1}
Dictionary after adding 3 elements:
{0: 'LIBED', 2: 'PYTHON', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'LIBED', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'LIBED', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Hello', '2': 'World'}}}
Accessing elements of a Dictionary: In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Example:
# accessing a element from a Dictionary
Dict = {1: 'LIBED', 'name': 'Python', 3: 'Tutorial'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using key:")
print(Dict[1])
Output:
Accessing a element using key:
Python
Accessing a element using key:
LIBED
Accessing an element of a nested dictionary: In order to access the value of any key in the nested dictionary, use indexing [] syntax.
Example:
# Creating a Dictionary
Dict = {'Dict1': {1: 'Python'}, 'Dict2': {'Name': 'Tutorial'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Python'}
Python
Tutorial
Dictionary Methods
Below are few Dictionary methods we commonly use:
clear()
The clear() method removes all items from the dictionary.
Syntax is dict.clear().
The clear() method doesn't take any parameters. The clear() method doesn't return any value.
Example:
# clear() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict1.clear()
print(dict1)
Output:
{}
copy()
The copy() method returns a shallow copy of the dictionary. The clear() method removes all items from the dictionary.
Syntax is dict.copy().
The copy() method doesn't take any parameters. This method doesn't modify the original, the dictionary just returns a copy of the dictionary.
Example:
# copy() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict2 = dict1.copy()
print(dict2)
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
fromkeys()
The fromkeys() method returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value.
Syntax is fromkeys(seq, val).
The parameters are:
seq— The sequence to be transformed into a dictionary.val— Initial values that need to be assigned to the generated keys. Defaults toNone.
A dictionary with keys mapped to None if no value is provided.
Example:
x = (1, 2, 3)
y = "Python"
dict1 = dict.fromkeys(x, y)
dict2 = dict.fromkeys(x)
print(dict1)
print(dict2)
Output:
{1: 'Python', 2: 'Python', 3: 'Python'}
{1: None, 2: None, 3: None}
get()
The get() method returns the value for the given key if present in the dictionary. If not, then it will return None.
Syntax is Dict.get(key, default=None).
The parameters are:
key— The key name of the item you want to return the value from.Value(Optional) — Value to be returned if the key is not found. The default value isNone.
Returns the value of the item with the specified key or the default value.
Example:
# get() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
print(dict1.get(1))
print(dict1.get(5, "Not found"))
Output:
Python
Not found
items()
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. In Python Dictionary, the items() method is used to return the list with all dictionary keys with values.
Syntax is dictionary.items().
This method takes no parameters.
Example:
# items() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
print(dict1.items())
Output:
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
keys()
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python.
Syntax is dict.keys().
There are no parameters. This view object changes according to the changes in the dictionary.
Example:
# keys() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict1[5] = "Oracle"
print(dict1.keys())
Output:
dict_keys([1, 2, 3, 4, 5])
pop()
Python dictionary pop() method removes and returns the value associated with the deleted key-value pair, if the key is present. It returns the default value if the key is not present. It generates KeyError, if the key is not present and default value is not specified.
Syntax is dict.pop(key, def).
The parameters are:
key— The key whose key-value pair has to be returned and removed.def— The default value to return if specified key is not present.
Example:
# pop() method
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict1.pop(4)
print(dict1)
dict2 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
x = dict2.pop(4)
print(x)
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby'}
Scala
popitem()
The popitem() method removes the last inserted key-value pair from the dictionary and returns a tuple containing the arbitrary key-value pair.
Syntax is dict.popitem().
There are no parameters for this method.
Example:
# popitem() method
dict2 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict2.popitem()
print(dict2)
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby'}
setdefault()
The setdefault() returns the value of a key if the key is in the dictionary. Else, it inserts a key with the default value to the dictionary. It returns None if the key is not in the dictionary and default_value is not specified.
Syntax is dict.setdefault(key, default_value).
It takes two parameters:
key— Key to be searched in the dictionary.default_value(optional) — Key with a valuedefault_valueis inserted to the dictionary if the key is not in the dictionary. If not provided, thedefault_valuewill beNone.
Example:
# setdefault() method
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = car.setdefault("model", "Bronco")
y = car.setdefault("color", "white")
print(x)
print(y)
print(car)
Output:
Mustang
white
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white'}
update()
The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Syntax is dict.update([other]).
This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters. It doesn't return any value.
Example:
# update() method
dict2 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict2.update({3: "Oracle"})
dict2.update({5: "HTML"})
print(dict2)
Output:
{1: 'Python', 2: 'Java', 3: 'Oracle', 4: 'Scala', 5: 'HTML'}
values()
The values() is an inbuilt method in the Python programming language that returns a view object that contains the values of the dictionary, as a list. If you use the type() method on the return value, you get a "dict_values".
Syntax is dictionary_name.values().
There are no parameters.
Example:
# values() method
dict2 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
print(dict2.values())
Output:
dict_values(['Python', 'Java', 'Ruby', 'Scala'])
del()
The del keyword removes the item with the specified key name.
Example:
# del() method
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
del thisdict["model"]
print(thisdict)
thisdict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
del thisdict1
print(thisdict1)
Output:
{'brand': 'Ford', 'year': 1964}
NameError: name 'thisdict1' is not defined