Professional Documents
Culture Documents
Dictionaries 1
Dictionaries 1
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 single value as an element,
Dictionary holds key:value pair. Key value is provided in the dictionary to make it more
optimized. XIF={1:”Alok”, 3:”Deepak”, 4:”Deepak”}
Note – Keys in a dictionary doesn’t allows Polymorphism (within a dictionary key cannot
be repeated).
Creating a Dictionary
Note – Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly.
Syntax for creating a dictionary:
<dictionary_name>={<key>:<value>, <key>:<value>………}
# empty dictionary
my_dict = {}
While indexing is used with other data types to access values, a dictionary uses keys . Keys
can be used either inside square brackets [] or with the get() 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: Alok
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output
Alok
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address
Giving just the name of dictionary in print( ) displays the entire contents of the dictionary,
as with all data types, but look at the following example and mark an interesting fact about
dictionaries.
Output
So we see unlike other sequences, the elements (key:value) of a dictionary do not have fix
order, they may appear in any order, so we say dictionaries are unordered. We cannot
access element as per specific order (no indexing of elements). The only way to access a
value is through its key. Thus we can say that keys act like indexes to access value from a
dictionary.
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for loop.
Output
1
9
25
49
81
In above program loop variable i will be assigned the keys of the dictionary squares, one at
a time, now we can access values for that particular key using squares[ i ]. As dictionaries
are unordered, the order of assignment of keys to variable i may be differ in every run.
So, we can access both keys and values form the same loop.
# Iterating through a Dictionary
d2={"alok":9908876910,"Kamal":7766554433,"Lalit":7192837465}
for i in d2:
print(i,”- ->”,d2[i]) # i will give key and d2[i] its corresponding value
Output
alok --> 9908876910
Accessing all Keys or all Values in one go is also possible. We can use <dictionary>.keys( ),
to see all the keys in dictionary, likewise <dictionary>.values( ) will return all the values in
one go.
# Accessing Keys and values in one go
d1={10:"alok",11:"Kamal",12:"Lalit",13:"Deepak"}
print(d1.keys())
print(d1.values())
Output
dict_keys([10, 11, 12, 13])
The keys() and values() function return all the keys or values in form of a sequence, we can
convert them, to other sequences. Example
# Converting Keys and values to List/Tuple
d1={10:"alok",11:"Kamal",12:"Lalit",13:"Deepak"}
L=list(d1.keys()) # Will convert collection of all keys to list
print (L)
T=tuple(d1.values())#Will convert collection of all values to tuple
print (T)
Output
[10, 11, 12, 13]
1. Unordered set: Key value pair or an element may appear in any order so they are
unordered set of elements.
2. Not a sequence: Unlike list, string or tuples dictionary is not a sequence as no
indexes are used.
3. Indexed by Keys, not numbers.
4. Keys in a Dictionary must be unique and immutable. The keys of a dictionary
identify a value, so keys must be of immutable type (not to be changed), we can use
string or number as key, even a tuple if contains all immutable elements , can be
used as a key. The values on other can be of any type.
#Mixed data type keys and values
dict1={1:"integer as key", "two":2,(3,"hello"):"tuple as key",
4:[12,"a"]}
print(dict1[1])#integer as key, string as value
print(dict1[“two”])#string as key, int as value
print(dict1[(3,"hello")])#Tuple as key, string value
print(dict1[4])# Int as key, List as value
Output
integer as key
2
tuple as key
[12, 'a']
5. Dictionaries are Mutable:- Like lists dictionaries are also mutable, we can change
value of a certain key in place using assignment operator:-
<dictionary>[key]=<new value>
For example in above dictionary dict1 we can change the value of key 1 by:-
#changing value of a key
dict1[1]=111
print(dict1[1])
the above statement will change the value of key 1 in the dictionary to 111 (not
only value changed but data type too.
An interesting fact, if the key does not exist in the dictionary, a new key:value pair
is added to the dictionary
#Adding new key:value pair
dict1[5]=”five” # Will add a new element
print(dict1)
Output
{1: 111, 'two': 2, (3, 'hello'): 'tuple as key', 4: [12, 'a'],
5: 'five'}
Creating Dictionary:- There are many ways for creating Python Dictionary:-
dd[“name”]=”Alok”
dd[“roll”]= 12
i) Specific key value pair as keyword arguments to dict(), Keys as arguments and
values as their value. The argument names (keys) are string type
# Keys and values as keyword arguments
s2=dict(name='alok',Class=11,roll=12)
print(s2)
output
{'name': 'alok', 'Class': 11, 'roll': 12}
output
{'name': 'alok', 'Class': 11, 'roll': 12}
iii) Specify keys and corresponding values separately:- In this method keys and
corresponding values are enclosed in parenthesis and are passed as an
argument to the zip() function, which is then given as argument to dict().
output
{'name': 'alok', 'Class': 11, 'roll': 12}
iv) Creating dictionary from sequences:- We can pass sequences (list or tuple) as
argument to dict(). The list/tuple passed is nested, having key and value as single
element.
output
{'name': 'alok', 'Class': 11, 'roll': 12}
{'name': 'alok', 'Class': 11, 'roll': 12}