Dictionary Unit IV
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 IV.ipynb?download=false 1/8
2/17/22, 12:55 PM Dictionary Unit IV
Out[13]:
In [6]:
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
y=thisdict.get("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'])
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)
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.
In [26]:
#Adding an item to the dictionary is done by using a new
# index key and assigning a value to it:
In [20]:
print(dir(dict))
In [23]:
d=['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',
print(len(d))
11
In [27]:
help(dict.clear)
Help on method_descriptor:
clear(...)
D.clear() -> None. Remove all items from D.
In [28]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
d.clear()
print(d)
{}
In [29]:
help(dict.copy)
Help on method_descriptor:
copy(...)
D.copy() -> a shallow copy of D
In [30]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
di=d.copy()
print(di)
In [31]:
help(dict.pop)
Help on method_descriptor:
pop(...)
D.pop(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=d.pop("model")
print(d)
print("value of pop item is=",x)
In [34]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.pop()
localhost:8888/nbconvert/html/Dictionary Unit IV.ipynb?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=d.pop()
3 print(d)
4 print("value of pop item is=",x)
In [35]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.pop("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=d.pop("color")
3 print(d)
4 print("value of pop item is=",x)
KeyError: 'color'
In [65]:
help(dict.popitem)
Help on method_descriptor:
popitem(self, /)
Remove and return a (key, value) pair as a 2-tuple.
In [66]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.popitem()
print(d)
print("value of pop item is=",x)
In [36]:
help(dict.items)
help(dict.keys)
help(dict.values)
Help on method_descriptor:
items(...)
D.items() -> a set-like object providing a view on D's items
keys(...)
D.keys() -> a set-like object providing a view on D's keys
Help on method_descriptor:
values(...)
D.values() -> an object providing a view on D's values
In [37]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
di=d.items()
dk=d.keys()
dv=d.values()
print(di)
print(dk)
print(dv)
In [39]:
for k in d.keys():
print(k)
brand
model
year
In [40]:
for v in d.values():
print(v)
Ford
Mustang
1964
In [41]:
for k,v in d.items():
print(k,":",v)
brand : Ford
model : Mustang
year : 1964
In [42]:
help(dict.fromkeys)
In [46]:
d1=dict
d2 = d1.fromkeys([1,2,3])
print(d2)
In [48]:
d1=dict
d2 = d1.fromkeys([1,2,3],5)
print(d2)
{1: 5, 2: 5, 3: 5}
In [49]:
d1=dict
d2 = d1.fromkeys([1,2,3],('a','b','c'))
print(d2)
{1: ('a', 'b', 'c'), 2: ('a', 'b', 'c'), 3: ('a', 'b', 'c')}
In [50]:
help(dict.setdefault)
Help on method_descriptor:
Return the value for key if key is in the dictionary, else default.
In [51]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.setdefault("brand")
print(x)
Ford
In [53]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.setdefault("brand","Honda")
print(x)
print(d)
Ford
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [54]:
d = {"brand": "Ford", "model": "Mustang", "year": 1964 }
x=d.setdefault("color","red")
print(x)
print(d)
red
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
In [55]:
help(dict.update)
Help on method_descriptor:
update(...)
D.update([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
In [58]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
car.update({"year":1978,"color": "White"})
print(car)
In [59]:
d = {'name': 'SER','roll':10}
d.update([('roll',11),('marks',89)])
print(d)
In [62]:
d = {'name': 'SER','roll':10}
d.update([('ro'),('ma')])
print(d)
In [63]:
d = {'name': 'SER','roll':10}
d.update([(1),(2)])
print(d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-63-85fc1d259afd> in <module>
1 d = {'name': 'SER','roll':10}
----> 2 d.update([(1),(2)])
3 print(d)