2/17/22, 12:55 PM Dictionary Unit IV
Dictionary
1. A dictionary is a collection which is unordered, changeable and indexed.
2. In Python dictionaries are written with curly({}) brackets, and an item in the dictionary is a key
and value pair.
3. Each key is separated from its value by a colon (:) and consecutive items are separated by
commas.
4. Syntax: dictionary_name = {key1:value1, key2:value2, key3:value3}
5. keys can be of any type
6. Dictionary keys are case sensitive. Two keys with same name but in different case are not same
in Python.
7. Dictionary is represented by dict class in python
creating a dictionary
In [4]:
d = {}
print(d)
print(type(d))
d1=dict()
print(d1)
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
print(thisdict)
{}
<class 'dict'>
{}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [10]:
d = dict([(1,1),(2,4),(3,9)])
d
{1: 1, 2: 4, 3: 9}
Out[10]:
In [11]:
d = dict([[1,1],[2,4],[3,9]])
d
{1: 1, 2: 4, 3: 9}
Out[11]:
In [12]:
d = dict(([1,1],[2,4],[3,9]))
d
{1: 1, 2: 4, 3: 9}
Out[12]:
In [13]:
d = dict(((1,1),(2,4),(3,9)))
d
{1: 1, 2: 4, 3: 9}
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 1/8
2/17/22, 12:55 PM Dictionary Unit IV
Out[13]:
Accessing items in dictionary
1. You can access the items of a dictionary by referring to its key name, inside square brackets:
2. There is also a method called get() that will give you the same result:
In [6]:
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
y=[Link]("model")
print(y)
Mustang
Mustang
Nested Dictionary
In [15]:
d = {'s1':{'name':'ABC','roll':1},
's2':{'name':'DEF','roll':2},
's3':{'name':'XYZ','roll':3}}
print(d)
{'s1': {'name': 'ABC', 'roll': 1}, 's2': {'name': 'DEF', 'roll': 2}, 's3': {'name': 'XY
Z', 'roll': 3}}
In [16]:
print(d['s2'])
{'name': 'DEF', 'roll': 2}
In [17]:
print(d['s2']['name'])
DEF
In [19]:
d['s2']['name'] = 'WER'
print(d)
{'s1': {'name': 'ABC', 'roll': 1}, 's2': {'name': 'WER', 'roll': 2}, 's3': {'name': 'XY
Z', 'roll': 3}}
Dictionary is mutable so modification in any item is allowed. but only value can
be changed by reffering its key.
In [1]:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 2/8
2/17/22, 12:55 PM Dictionary Unit IV
Looping through Dictionary
When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
In [7]:
thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}
for x in thisdict:
print(x)
brand
model
year
In [8]:
thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}
for x in thisdict:
print(x, thisdict[x]) # accessing values
brand Ford
model Mustang
year 1964
In [9]:
thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}
for x in enumerate(thisdict):
print(x)
(0, 'brand')
(1, 'model')
(2, 'year')
In [24]:
#To determine if a specified key is present in a dictionary use the in keyword.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Yes, 'model' is one of the keys in the thisdict dictionary
In [26]:
#Adding an item to the dictionary is done by using a new
# index key and assigning a value to it:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
print(thisdict)
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
In [20]:
print(dir(dict))
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq_
_', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__
init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__ne
w__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setit
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 3/8
2/17/22, 12:55 PM Dictionary Unit IV
em__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get',
'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
In [23]:
d=['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',
print(len(d))
11
In [27]:
help([Link])
Help on method_descriptor:
clear(...)
[Link]() -> None. Remove all items from D.
In [28]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
[Link]()
print(d)
{}
In [29]:
help([Link])
Help on method_descriptor:
copy(...)
[Link]() -> a shallow copy of D
In [30]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
di=[Link]()
print(di)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [31]:
help([Link])
Help on method_descriptor:
pop(...)
[Link](k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
In [33]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]("model")
print(d)
print("value of pop item is=",x)
{'brand': 'Ford', 'year': 1964}
value of pop item is= Mustang
In [34]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]()
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 4/8
2/17/22, 12:55 PM Dictionary Unit IV
print(d)
print("value of pop item is=",x)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-6d79b525e2d4> in <module>
1 d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
----> 2 x=[Link]()
3 print(d)
4 print("value of pop item is=",x)
TypeError: pop expected at least 1 argument, got 0
In [35]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]("color")
print(d)
print("value of pop item is=",x)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-35-2f15d53b6093> in <module>
1 d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
----> 2 x=[Link]("color")
3 print(d)
4 print("value of pop item is=",x)
KeyError: 'color'
In [65]:
help([Link])
Help on method_descriptor:
popitem(self, /)
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
In [66]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]()
print(d)
print("value of pop item is=",x)
{'brand': 'Ford', 'model': 'Mustang'}
value of pop item is= ('year', 1964)
In [36]:
help([Link])
help([Link])
help([Link])
Help on method_descriptor:
items(...)
[Link]() -> a set-like object providing a view on D's items
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 5/8
2/17/22, 12:55 PM Dictionary Unit IV
Help on method_descriptor:
keys(...)
[Link]() -> a set-like object providing a view on D's keys
Help on method_descriptor:
values(...)
[Link]() -> an object providing a view on D's values
In [37]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
di=[Link]()
dk=[Link]()
dv=[Link]()
print(di)
print(dk)
print(dv)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
In [39]:
for k in [Link]():
print(k)
brand
model
year
In [40]:
for v in [Link]():
print(v)
Ford
Mustang
1964
In [41]:
for k,v in [Link]():
print(k,":",v)
brand : Ford
model : Mustang
year : 1964
In [42]:
help([Link])
Help on built-in function fromkeys:
fromkeys(iterable, value=None, /) method of [Link] instance
Create a new dictionary with keys from iterable and values set to value.
In [46]:
d1=dict
d2 = [Link]([1,2,3])
print(d2)
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 6/8
2/17/22, 12:55 PM Dictionary Unit IV
{1: None, 2: None, 3: None}
In [48]:
d1=dict
d2 = [Link]([1,2,3],5)
print(d2)
{1: 5, 2: 5, 3: 5}
In [49]:
d1=dict
d2 = [Link]([1,2,3],('a','b','c'))
print(d2)
{1: ('a', 'b', 'c'), 2: ('a', 'b', 'c'), 3: ('a', 'b', 'c')}
In [50]:
help([Link])
Help on method_descriptor:
setdefault(self, key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
In [51]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]("brand")
print(x)
Ford
In [53]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]("brand","Honda")
print(x)
print(d)
Ford
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [54]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=[Link]("color","red")
print(x)
print(d)
red
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
In [55]:
help([Link])
Help on method_descriptor:
update(...)
[Link]([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 7/8
2/17/22, 12:55 PM Dictionary Unit IV
In either case, this is followed by: for k in F: D[k] = F[k]
In [58]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
[Link]({"year":1978,"color": "White"})
print(car)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1978, 'color': 'White'}
In [59]:
d = {'name': 'SER','roll':10}
[Link]([('roll',11),('marks',89)])
print(d)
{'name': 'SER', 'roll': 11, 'marks': 89}
In [62]:
d = {'name': 'SER','roll':10}
[Link]([('ro'),('ma')])
print(d)
{'name': 'SER', 'roll': 10, 'r': 'o', 'm': 'a'}
In [63]:
d = {'name': 'SER','roll':10}
[Link]([(1),(2)])
print(d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-63-85fc1d259afd> in <module>
1 d = {'name': 'SER','roll':10}
----> 2 [Link]([(1),(2)])
3 print(d)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
localhost:8888/nbconvert/html/Dictionary Unit [Link]?download=false 8/8