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 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
4. 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
7. 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)
8. 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
9. 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)
10. 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
>>>
11. 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
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.
18. 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.
19. 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()))
20. 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)