[go: up one dir, main page]

0% found this document useful (0 votes)
63 views60 pages

Dictionary

The document provides information on dictionaries in Python. Some key points: - Dictionaries are used to store mappings of unique keys to values. They are written with curly braces like {'key1':'value1'}. - Keys must be immutable but values can be any type. Values are accessed via keys rather than position. - Common dictionary methods include updating and adding items with square brackets, removing items with del, and built-in functions like len(), str(), type() etc. - Loops can be used to count frequencies of letters in a string by using a dictionary to map each letter to its count.

Uploaded by

Manan kansara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views60 pages

Dictionary

The document provides information on dictionaries in Python. Some key points: - Dictionaries are used to store mappings of unique keys to values. They are written with curly braces like {'key1':'value1'}. - Keys must be immutable but values can be any type. Values are accessed via keys rather than position. - Common dictionary methods include updating and adding items with square brackets, removing items with del, and built-in functions like len(), str(), type() etc. - Loops can be used to count frequencies of letters in a string by using a dictionary to map each letter to its count.

Uploaded by

Manan kansara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

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:

dict1 = {'Name': 'abc', 'Age': 7}


dict2 = {'Name': 'abc', 'Age': 7}
dict3 = {'Name': 'abc', 'Age': 27}
dict4 = {'Name': 'AAc', 'Age': 7}
dict5 = {'Name': 'ABc', 'Age': 7}
dict6 = {'Name': 'abc', 'Age': 31}
dict7 = {'Name': 'pqr'}
print "Return Value : %d" % cmp (dict1, dict2)
#print cmp(dict1, dict2)
print "Return Value : %d" % cmp (dict2, dict3)
print "Return Value : %d" % cmp (dict1, dict4)
print "Return Value : %d" % cmp (dict4, dict5)
print "Return Value : %d" % cmp (dict4, dict6)
print "Return Value : %d" % cmp (dict1, dict7)
Output:
Return Value : 0
Return Value : -1
Return Value : 1
Return Value : -1
Return Value : -1
Return Value : 1
 Python 3: cmp does not exist
Ex:
if dict1==dict2:
print(“True”)
2. len(dict)
Gives the total length of the dictionary. This would
be equal to the number of items in the dictionary.
 Syntax:
len(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Length : “, len(dict))
dict1 = {}
print("Length : “, len(dict1))

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])

seq -- This is the list of values which would be used


for dictionary keys preparation.
value -- This is optional, if provided then value would
be set to this value.
Ex:
seq = ('name', 'age')
dict = dict.fromkeys(seq)
print("New Dictionary : “, str(dict))
dict = dict.fromkeys(seq, 10)
print("New Dictionary : “, str(dict))

Output:
New Dictionary : {'name': None, 'age': None}
New Dictionary : {'name': 10, 'age': 10}
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]

vowels = dict.fromkeys(keys, value)


print(vowels)

# updating the value


value.append(2)
print(vowels)
 Output:
{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}
{'a': [1, 2], 'u': [1, 2], 'o': [1, 2], 'e': [1, 2], 'i': [1,
2]}
4. dict.get(key, default=None)
Returns a value for the given key. If key is not
available then returns default value None.

 Syntax:
dict.get(key, default=None)

key -- This is the Key to be searched in the


dictionary.
default -- This is the Value to be returned in case key
does not exist.
Ex:
dict = {'Name': 'Zabra', 'Age': 7}
print("Value : " , dict.get('Age’))
print("Value : “, dict.get('Education', ‘Never’))
print("Value : “, dict.get('Gender’))
print(dict)

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()

dict = {'Name': 'Zara', 'Age': 7}


print(min(dict))
print(max(dict))
print(dict.pop('Name'))
print(dict)
print(dict.pop('Age'))
print(dict)
dict['N']='Zara'
dict['A']=7
print(dict)
print(dict.popitem())
print(dict)
 Output:
Age
Name
Zara
{'Age': 7}
7
{}
{'N': 'Zara', 'A': 7}
('A', 7)
{'N': 'Zara'}
Looping and dictionaries

Problem: You are given a string and you want to


count how many times each letter appears.

 The for loop traverses the string. Each time through


the loop, if the character c is not in the dictionary,
we create a new item with key c and the initial
value 1 (since we have seen this letter once). If c is
already in the dictionary we increment d[c].
 Ex:
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)

 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)

You might also like