Dictionary
Dictionary
in Python
Dictionary is one of the data type in python.
It is mapping between key and values. The
association of a key and a value is called a key-
value pair or sometimes an item.
Lists are ordered set of objects, whereas dictionaries
are unordered sets.
Items in dictionaries are accessed via keys and not
via their position.
Syntax of dictionary:
{key1:value1, key2:value2,...}
Example:
{1:’abc’,2:’xyz’}
Empty dictionary is denoted by { }.
Keys are unique within a dictionary while values
may not be. The values of a dictionary can be of
any type, but the keys must be immutable.
The function dict creates a new dictionary with no items.
Because dict is the name of a built-in function, you
should avoid using it as a variable name.
Ex:
a = dict()
print(a)
Output:
{}
a = {}
print(a)
Ex:
a = dict()
print(dict)
Output:
<type 'dict'>
Adding & Accessing items
To add items to the dictionary, you can use
square brackets:
Ex:
a=dict()
a[1] = ‘abc‘
print(a)
Output:
{1: 'abc'}
Ex:
a=dict()
a[‘a’] = ‘abc‘
a['b'] = 'pqr'
print(a)
print(a[‘b’])
Output:
{'a': 'abc', 'b': 'pqr'}
pqr
Ex:
a=dict()
a[b] = 'abc‘
print(a)
Output:
NameError: name 'b' is not defined
Ex:
dict={1:'Name',2:'xyz',2:'abc'}
print(dict)
print(dict[1])
print(dict[2])
Output:
{1: 'Name', 2: 'abc'}
Name
abc
Attempting to access a data item with a key, which is
not part of dictionary will result in error.
Ex:
a = {'a':'abc','b':'pqr'}
print(a)
print(a['a’])
print(a[‘c’])
Output:
{'a': 'abc', 'b': 'pqr'}
abc
KeyError: 'c'
Updating dictionary
(1) By adding new items/modifying existing
entry:
Ex:
a = {'a': 'abc', 'b': 'pqr'}
a[‘a’]=‘zxc’
a['c']=8
print(a)
Output:
{'a': 'zxc', 'b': 'pqr', 'c': 8}
(2) Removing dictionary:
Ex:
a={1:'abc', 2:'pqr'}
del a[1]
print(a)
del a[2]
print(a)
a[1]='abc'
print(a)
a.clear()
print(a)
del a
print(a)
Output:
{2: 'pqr'}
{}
{1: 'abc'}
{}
NameError: name 'a' is not defined
Built-in dictionary functions
1. cmp(dict1, dict2)
cmp() compares two dictionaries based
on key and values.
Syntax:
cmp(dict1, dict2)
This method returns 0 if both dictionaries
are equal, -1 if dict1 < dict2 and 1 if dict1
> dic2.
Ex:
Output:
Length : 2
Length : 0
3. str(dict)
Produces a printable string representation of a
dictionary.
Syntax:
str(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Equivalent String : “, str (dict))
print(dict)
Output:
Equivalent String : {'Age': 7, 'Name': 'Zara'}
{'Age': 7, 'Name': 'Zara'}
4. type(variable)
Returns the type of the passed variable. If passed
variable is dictionary, then it would return a
dictionary type.
Syntax:
type(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Variable Type : “, type (dict))
Output:
Variable Type : <class 'dict'>
Built-in dictionary methods
1. dict.clear()
Removes all elements of dictionary dict.
Syntax:
dict.clear()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Start Len : “, len(dict))
dict.clear()
print("End Len : “, len(dict))
Output:
Start Len : 2
End Len : 0
2. dict.copy()
Returns a copy of dictionary dict
Syntax:
dict.copy()
Ex:
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print("New Dictionary : “, str(dict2))
Output:
New Dictionary : {'Age': 7, 'Name': 'Zara'}
3. dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.
Syntax:
dict.fromkeys(seq[, value])
Output:
New Dictionary : {'name': None, 'age': None}
New Dictionary : {'name': 10, 'age': 10}
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]
Syntax:
dict.get(key, default=None)
Output:
Value : 7
Value : Never
Value : None
{'Age': 7, 'Name': 'Zabra'}
5. dict.has_key(key)
Returns true if key is in dictionary dict, false
otherwise
Syntax:
dict.has_key(key)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print(“Answer : “, dict.has_key('Age’))
print(" Answer : “, dict.has_key('Education’))
Output:
Answer : True
Answer : False
Python 3: has_key does not exist.
dict1 = {'Name': 'Zara', 'Age': 7}
if 'Age' in dict1:
print(‘True’)
6. dict.items()
Returns a list of dict's (key, value) tuple pairs
Syntax:
dict.items()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print(“Answer : “, list(dict.items()))
Output:
Answer : [('Name', 'Zara'), ('Age', 7)]
7. dict.keys()
Returns list of dictionary dict's keys
Syntax:
dict.keys()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict1 = {}
print(“Key : “, dict.keys())
print("Value : “, dict1.keys())
Output:
Key : ['Age', 'Name']
Value : []
8. dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default
if key is not already in dict
Syntax:
dict.setdefault(key, default=None)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Value : ", dict.setdefault('Age', None))
print("Value : “, dict.setdefault('Education', 'Never’))
print("Value : ", dict.setdefault('Gender’))
print(dict)
Output:
Value : 7
Value : Never
Value : None
{'Name': 'Zara', 'Age’: 7, 'Education’: 'Never’, 'Gender’:
None}
Difference between get() and
setdefault() methods:
data = {}
x = data.get('key',10)
print(x) #Output:10
print(data) #Output: {}
data = {}
x = data.setdefault('key',10)
print(x) #Output:10
print(data) #Output: {'key': 10}
9. dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict. This
function does not return anything.
Syntax:
dict.update(dict2)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Gender': 'female' }
dict.update(dict2)
print("Value : “, dict)
print(dict2)
Output:
Value : {'Name': 'Zara', 'Age': 7, 'Gender': 'female'}
{'Gender': 'female'}
10. dict.values()
Returns list of dictionary dict's values
Syntax:
dict.values()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {}
print("Value : “, dict.values())
print("Value : “, dict2.values())
Output:
Value : [7, 'Zara']
Value : []
Ex:
a = {1: 'abc', 2: 'pqr', 3: 'xyz'}
print(1 in a)
print(4 in a)
val = a.values()
print('pqr' in val)
Output:
True
False
True
11. pop(), popitem()
Output:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
We can use get to write our loop more concisely.
Because the get method automatically handles the
case where a key is not in a dictionary, we can
reduce four lines down to one and eliminate the if
statement.
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
If you use a dictionary as the sequence in a for
statement, it traverses the keys of the dictionary. This
loop prints each key and the corresponding value.
Ex:
counts = { 1:'abc',2:'pqr',3:'xyz'}
for key in counts:
print(key, counts[key])
Output:
1 abc
2 pqr
3 xyz
Problem:
Find all the entries in a dictionary with a value above
ten.
d = { ‘abc' : 1 , ‘pqr' : 42, ‘xyz': 100}
for i in d:
if d[i] > 10 :
print(i, d[i])
Output:
pqr 42
xyz 100
Problem:
Print keys in alphabetical order.
d = {'chuck' : 1 , 'annie' : 42, 'jan': 100}
lst = list(d.keys()) # lst = list(d)
print(lst)
l = sorted(lst)
for i in l:
print(i, d[i])
Output:
['chuck', 'annie', 'jan']
annie 42
chuck 1
jan 100
With a given integral number n, write a
program to generate a dictionary that
contains (i, i*i). Suppose the following
input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Solution:
n=int(input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print(d)