PYTHON-LIST - J - Dictionary
PYTHON-LIST - J - Dictionary
PYTHON-LIST - J - Dictionary
172.Python - Dictionary
180.Multi-dimensional Dictionary
1|P a ge
Python - Dictionary
The dictionary is an unordered collection that contains key:value pairs separated by commas
inside curly brackets. Dictionaries are optimized to retrieve values when the key is known.
Example: Dictionary
Above, capitals is a dictionary object which contains key-value pairs inside { }. The left side of : is
a key, and the right side is a value. The key should be unique and an immutable object. A
number, string or tuple can be used as key. Hence, the following dictionaries are also valid:
d = {} # empty dictionary
decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string
value
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value
However, a dictionary with a list as a key is not valid, as the list is mutable:
2|P a ge
The same key cannot appear more than once in a collection. If the key appears more than once,
only the last will be retained. The value can be of any data type. One value can be assigned to
more than one key.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
As you can see from above, we can also create a dictionary using the built-in dict() function.
3|P a ge
Using the dict() constructor method.
A dictionary can also be created using the dict() constructor method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On
the other hand, the get() method returns None if the key is not found.
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
4|P a ge
print(my_dict['address'])
KeyError: 'address'
If the key is already present, then the existing value gets updated. In case the key is not present,
a new (key: value) pair is added to the dictionary.
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
Output
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from
the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
5|P a ge
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
Output
True
True
False
6|P a ge
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output
1
9
25
49
81
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key
pop(key[,d])
is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and
setdefault(key[,d])
returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values
7|P a ge
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to
perform different tasks.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
Example: keys()
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg'])
8|P a ge
Check Dictionary Keys
You can check whether a paritular key exists in a dictionary collection or not usng the in or not
in keywords, as shown below. Note that it only checks for keys not values.
Multi-dimensional Dictionary
Let's assume there are three dictionary objects, as below:
Example: Dictionary
>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}
Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll
number as key and the above dictionaries at their value.
The student object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as values to
keys 1, 2, and 3, respectively. The students[1] returns d1.
9|P a ge
Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
# Creating a Dictionary
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
U:Python-Dictionary Program-(1-15)
10 | P a g e