Dictionaries
MAPPING
CONTENT
Characteristic: key-value pair, un ordered, unique pairs(keys),mutable, keys-immutable type
Methods of creating a dictionary:
{ : }
dict(): dict(k1=v1,k2=v2), dict( ((k1,v1) , (k2,v2)) ) dict({k1:v1}), dict(zip( (k1,k2),(v1,v2) ) ), dict.fromkeys(keys,
single value)
Traversing : in, items( )
Adding/updating elements: D[key]=value, setdefault ,update
Deleting elements: del, pop, popitem, clear
Pretty printing –json.dumps()
Dictionary methods: get, keys, values, copy
A Story of Two Collections..
List, tuple, string
A linear collection of values that stay in order
Dictionary
A “bag” of values, each with its own label
Dictionaries
Dictionaries are Python’s most powerful data collection
Dictionaries allow us to do fast database-like operations in Python
Dictionaries have different names in different languages
◦ Associative Arrays - Perl / Php
◦ Properties or Map or HashMap - Java
◦ Property Bag - C# / .Net
http://en.wikipedia.org/wiki/Associative_array
purse = dict()
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
names = {}
names['B/101'] = "Anusha"
names['B/102'] = "Athish"
print(names)
{'money': 12, 'candy': 3, 'tissues': 75}
{'B/101': 'Anusha', 'B/102': 'Athish'}
Creating a
dictionary
{ : }
DICT(): DICT(K1=V1,K2=V2), DICT( ((K1,V1) , (K2,V2)) )
DICT({K1:V1}), DICT(ZIP( (K1,K2),(V1,V2) ) ), DICT.FROMKEYS(KEYS,
SINGLE VALUE)
List versus Dictionary
Lists index their entries based on the position in the list
Dictionaries are like bags - no order
So we index the things we put in the dictionary with a “lookup tag”
>>> lst = list()
>>> lst.append(21)
>>> lst.append(183)
>>> print(lst)
>>> lst[0] = 23
>>> print (lst)
>>> ddd = dict()
>>> ddd['age'] = 21
>>> ddd['course'] = 182
>>> print(ddd)
>>> ddd['age'] = 23
>>> print(ddd)
Dictionary Tracebacks
It is an error to reference a key which is not in the dictionary
We can use the in operator to see if a key is in the dictionary
>>> ccc = dict()
>>> print ccc[‘January']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>KeyError: ‘January'
>>> print (‘January' in ccc)
False
When we encounter a new name, we need to add a new entry in the dictionary and if this
the second or later time we have seen the name, we simply add one to the count in the
dictionary under that name
counts = dict()
names = ['Amrita', 'Ayush', 'Shriyans','Ayush', 'Rithvik']
for i in names :
if i not in counts:
counts[i] = 1
else :
counts[i] = counts[i] + 1
print(counts)
Two Iteration Variables!
We loop through the key-value pairs in a
dictionary using *two* iteration variables
During each iteration, the first variable is
the key and the second variable is the
corresponding value for the key
>>> j = { ‘Feb' : 1 , ‘Apr' : 42, 'jan': 100}
>>> for a,b in j.items() :
... print (a, b)
...
Feb 1
Apr 42
jan 100
>>>
WAP to create a dictionary company to store company
details like its name and its URL. The company’s
name is treated as key and URL as value. Display all
the company’s names and its URL
Adding/updating elements:
D[key]=value
d={'jan':31}
d['feb']=28
d
{'jan': 31, 'feb': 28}
setdefault
d.setdefault('mar',31)
31
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.setdefault('jan',30)
31
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.setdefault('extra')
d
{'jan': 31, 'feb': 28, 'mar': 31, 'extra':
None}
update
d1={'apr':30,'may':31}
d.update(d1)
d
{'jan': 31, 'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may':
31}
Deleting elements
del
d
{'jan': 31, 'feb': 28, 'mar': 31,
'extra': None, 'apr': 30, 'may':
31}
del d['extra']
d
{'jan': 31, 'feb': 28, 'mar': 31,
'apr': 30, 'may': 31}
pop, popitem, clear
d.pop('may')
31
d
{'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30}
d.popitem()
('apr', 30)
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.clear()
d
{}
Pretty printing –json.dumps()
d
{'jan': 31, 'feb': 28, 'mar': 31}
import json
print(json.dumps(d,indent=2))
{
"jan": 31,
"feb": 28,
"mar": 31
}
JSON: JavaScript Object Notation is a format for
structuring data. It is mainly used for storing and
transferring data between the browser and the server.
Python too supports JSON with a built-in package called
json. This package provides all the necessary tools for
working with JSON Objects including parsing, serializing,
deserializing, and many more.
Dictionary methods:
get keys, values copy
d
{'jan': 31, 'feb': 28, 'mar':
31}
d.get('apr',"not found")
'not found'
d.get('jan')
31
list(d.keys())
['jan', 'feb', 'mar']
list(d.values())
[31, 28, 31]
d1=d
id(d)
1825985322112
id(d1)
1825985322112
d1=d.copy()
id(d1)
1825985315904
sorted, reversed
D1
{'Apr': 30, 'Jun': 30, 'Sep': 30}
sorted(D1)
['Apr', 'Jun', 'Sep']
sorted(D1,reverse=True)
['Sep', 'Jun', 'Apr']
Retrieving lists of Keys and Values
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> print list(jjj)
['jan', 'chuck', 'fred']
>>> print jjj.keys()
['jan', 'chuck', 'fred']
>>> print jjj.values()
[100, 1, 42]
>>> print jjj.items()
[('jan', 100), ('chuck', 1), ('fred', 42)]
Important points about Dictionaries:
◦ Collection of key – value pairs
◦ Use the key not the index
◦ Key order is not guaranteed.
◦ Attempting to access a key that doesn’t exist causes error.
◦ Dictionaries are mutable. But give a non-mutable type as key (strings,integers,a tuple of
numbers or strings)
◦ But value can be of any type
◦ Unique keys , but values for any unique keys can be same.
◦ Storing a dictionary inside another dictionary
◦ Ex: emp = {‘Swati’ : {‘age’ : 24,’job’: ‘S/E’}, ‘Riya’ : {‘age’ : 22,’job’: ‘Acc’}
◦ You can add elements, update elements, delete elements.
◦ You can clear a dictionary.
1.What’s wrong with the following code?
S = { [2,3,4] : “Numbers”}
2.What’s the output?
Optional = { ‘Rahul’ : ‘Computers’,’Shreyas’ : ‘Economics’}
print(“Optional subject: Rahul: ”, Optional[‘Rahul’])
3. What’s the output?
Optional = { 'Tahul' : 'Computers','Shreyas' : 'Economics'}
a = list(Optional.keys())
print(a)
print(tuple(Optional.values()))
4. Can 2 keys of a dictionary be same? Can the values of 2 unique
keys be same?
5.Will this be an error?
Optional = dict(Name = "Sahil", Subject = 'Economics')
print(Optional)
What is the output?
1) Optional = dict(Name = "Sahil", Subject = 'Economics')
print(Optional)
2) Optional = dict({Name : “Sahil", Subject : 'Economics‘})
print(Optional)
3) Optional = dict(zip( ('Name','Subject'),("Sahil", 'Economics') ) )
print(Optional)
4) Optional = dict( [ [ 'Name','John‘ ] , [ "Subject", 'Economics'] ] )
print(Optional)
5) Optional = dict((('Name','John'),("Subject", 'Economics')))
print(Optional)

Dictionaries.pptx

  • 1.
  • 2.
    CONTENT Characteristic: key-value pair,un ordered, unique pairs(keys),mutable, keys-immutable type Methods of creating a dictionary: { : } dict(): dict(k1=v1,k2=v2), dict( ((k1,v1) , (k2,v2)) ) dict({k1:v1}), dict(zip( (k1,k2),(v1,v2) ) ), dict.fromkeys(keys, single value) Traversing : in, items( ) Adding/updating elements: D[key]=value, setdefault ,update Deleting elements: del, pop, popitem, clear Pretty printing –json.dumps() Dictionary methods: get, keys, values, copy
  • 3.
    A Story ofTwo Collections.. List, tuple, string A linear collection of values that stay in order Dictionary A “bag” of values, each with its own label
  • 4.
    Dictionaries Dictionaries are Python’smost powerful data collection Dictionaries allow us to do fast database-like operations in Python Dictionaries have different names in different languages ◦ Associative Arrays - Perl / Php ◦ Properties or Map or HashMap - Java ◦ Property Bag - C# / .Net http://en.wikipedia.org/wiki/Associative_array
  • 5.
    purse = dict() purse['money']= 12 purse['candy'] = 3 purse['tissues'] = 75 print(purse) names = {} names['B/101'] = "Anusha" names['B/102'] = "Athish" print(names) {'money': 12, 'candy': 3, 'tissues': 75} {'B/101': 'Anusha', 'B/102': 'Athish'}
  • 6.
    Creating a dictionary { :} DICT(): DICT(K1=V1,K2=V2), DICT( ((K1,V1) , (K2,V2)) ) DICT({K1:V1}), DICT(ZIP( (K1,K2),(V1,V2) ) ), DICT.FROMKEYS(KEYS, SINGLE VALUE)
  • 7.
    List versus Dictionary Listsindex their entries based on the position in the list Dictionaries are like bags - no order So we index the things we put in the dictionary with a “lookup tag” >>> lst = list() >>> lst.append(21) >>> lst.append(183) >>> print(lst) >>> lst[0] = 23 >>> print (lst) >>> ddd = dict() >>> ddd['age'] = 21 >>> ddd['course'] = 182 >>> print(ddd) >>> ddd['age'] = 23 >>> print(ddd)
  • 8.
    Dictionary Tracebacks It isan error to reference a key which is not in the dictionary We can use the in operator to see if a key is in the dictionary >>> ccc = dict() >>> print ccc[‘January'] Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: ‘January' >>> print (‘January' in ccc) False
  • 9.
    When we encountera new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name counts = dict() names = ['Amrita', 'Ayush', 'Shriyans','Ayush', 'Rithvik'] for i in names : if i not in counts: counts[i] = 1 else : counts[i] = counts[i] + 1 print(counts)
  • 10.
    Two Iteration Variables! Weloop through the key-value pairs in a dictionary using *two* iteration variables During each iteration, the first variable is the key and the second variable is the corresponding value for the key >>> j = { ‘Feb' : 1 , ‘Apr' : 42, 'jan': 100} >>> for a,b in j.items() : ... print (a, b) ... Feb 1 Apr 42 jan 100 >>>
  • 11.
    WAP to createa dictionary company to store company details like its name and its URL. The company’s name is treated as key and URL as value. Display all the company’s names and its URL
  • 12.
    Adding/updating elements: D[key]=value d={'jan':31} d['feb']=28 d {'jan': 31,'feb': 28} setdefault d.setdefault('mar',31) 31 d {'jan': 31, 'feb': 28, 'mar': 31} d.setdefault('jan',30) 31 d {'jan': 31, 'feb': 28, 'mar': 31} d.setdefault('extra') d {'jan': 31, 'feb': 28, 'mar': 31, 'extra': None} update d1={'apr':30,'may':31} d.update(d1) d {'jan': 31, 'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may': 31}
  • 13.
    Deleting elements del d {'jan': 31,'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may': 31} del d['extra'] d {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30, 'may': 31} pop, popitem, clear d.pop('may') 31 d {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30} d.popitem() ('apr', 30) d {'jan': 31, 'feb': 28, 'mar': 31} d.clear() d {}
  • 14.
    Pretty printing –json.dumps() d {'jan':31, 'feb': 28, 'mar': 31} import json print(json.dumps(d,indent=2)) { "jan": 31, "feb": 28, "mar": 31 } JSON: JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called json. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and many more.
  • 15.
    Dictionary methods: get keys,values copy d {'jan': 31, 'feb': 28, 'mar': 31} d.get('apr',"not found") 'not found' d.get('jan') 31 list(d.keys()) ['jan', 'feb', 'mar'] list(d.values()) [31, 28, 31] d1=d id(d) 1825985322112 id(d1) 1825985322112 d1=d.copy() id(d1) 1825985315904
  • 16.
    sorted, reversed D1 {'Apr': 30,'Jun': 30, 'Sep': 30} sorted(D1) ['Apr', 'Jun', 'Sep'] sorted(D1,reverse=True) ['Sep', 'Jun', 'Apr']
  • 17.
    Retrieving lists ofKeys and Values >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print list(jjj) ['jan', 'chuck', 'fred'] >>> print jjj.keys() ['jan', 'chuck', 'fred'] >>> print jjj.values() [100, 1, 42] >>> print jjj.items() [('jan', 100), ('chuck', 1), ('fred', 42)]
  • 18.
    Important points aboutDictionaries: ◦ Collection of key – value pairs ◦ Use the key not the index ◦ Key order is not guaranteed. ◦ Attempting to access a key that doesn’t exist causes error. ◦ Dictionaries are mutable. But give a non-mutable type as key (strings,integers,a tuple of numbers or strings) ◦ But value can be of any type ◦ Unique keys , but values for any unique keys can be same. ◦ Storing a dictionary inside another dictionary ◦ Ex: emp = {‘Swati’ : {‘age’ : 24,’job’: ‘S/E’}, ‘Riya’ : {‘age’ : 22,’job’: ‘Acc’} ◦ You can add elements, update elements, delete elements. ◦ You can clear a dictionary.
  • 19.
    1.What’s wrong withthe following code? S = { [2,3,4] : “Numbers”} 2.What’s the output? Optional = { ‘Rahul’ : ‘Computers’,’Shreyas’ : ‘Economics’} print(“Optional subject: Rahul: ”, Optional[‘Rahul’]) 3. What’s the output? Optional = { 'Tahul' : 'Computers','Shreyas' : 'Economics'} a = list(Optional.keys()) print(a) print(tuple(Optional.values()))
  • 20.
    4. Can 2keys of a dictionary be same? Can the values of 2 unique keys be same? 5.Will this be an error? Optional = dict(Name = "Sahil", Subject = 'Economics') print(Optional)
  • 21.
    What is theoutput? 1) Optional = dict(Name = "Sahil", Subject = 'Economics') print(Optional) 2) Optional = dict({Name : “Sahil", Subject : 'Economics‘}) print(Optional) 3) Optional = dict(zip( ('Name','Subject'),("Sahil", 'Economics') ) ) print(Optional) 4) Optional = dict( [ [ 'Name','John‘ ] , [ "Subject", 'Economics'] ] ) print(Optional) 5) Optional = dict((('Name','John'),("Subject", 'Economics'))) print(Optional)