Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d26360e

Browse files
committed
Added Namedtuple basic operation
1 parent 0bbfd83 commit d26360e

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Collections/namedtuple_basic.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#Like dictionaries it also contains keys that are hashed to a particular value.
2+
#It supports both access from key value and iteration
3+
from collections import namedtuple,col
4+
5+
nd1 = namedtuple('Student',['name','age','DOB'])
6+
S = Student('suman','20','2612000')
7+
print ("The Student age using index is : ",end ="")
8+
print (S[1])
9+
#The Student age using index is : 20
10+
print ("The Student name using keyname is : ",end ="")
11+
print (S.name)
12+
#The Student name using keyname is : suman
13+
14+
#this can also be accessed using getattr
15+
print ("The Student DOB using getattr() is : ",end ="")
16+
print (getattr(S,'DOB'))
17+
#The Student DOB using getattr() is : 2612000
18+
19+
#some methods that can be used to convert other collections into namedtuple
20+
nd2 = col.namedtuple('Employee',['name','city','salary'])
21+
my_list = ['Suman','Bangalore','100000']
22+
e1 = nd2._make(my_list)
23+
print(e1)
24+
#Employee(name='Asim', city='Delhi', salary='25000')
25+

Collections/orderdict_basic.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#It is a dictionary subclass that remembers the order that keys we re first inserted.
2+
from collections import OrderDict
3+
od1 = OrderDict()
4+
od1['a'] = 1
5+
od1['b'] =2
6+
od1['c'] = 3
7+
od1['d'] = 4
8+
for key,value in od1.items():
9+
print(key,value)
10+
11+
#answer
12+
# ('a', 1)
13+
# ('b', 2)
14+
# ('c', 3)
15+
# ('d', 4)
16+
17+
# if the value of a certain key is changed the position of the key remain unchanged
18+
od2 = OrderDict()
19+
od2['a'] = 1
20+
od2['b'] =2
21+
od2['c'] = 3
22+
od2['d'] = 4
23+
for key,value in od2.items():
24+
print(key,value)
25+
#answer
26+
# ('a', 1)
27+
# ('b', 2)
28+
# ('c', 3)
29+
# ('d', 4)
30+
od2['c'] = 5
31+
for key,value in od2.items():
32+
print(key,value)
33+
#answer
34+
# ('a', 1)
35+
# ('b', 2)
36+
# ('c', 5)
37+
# ('d', 4)
38+
39+
# Deleting and reinserting the same key will push it to the back as orderdict however maintains the order of insertion
40+
# It can be used as a stack with the help of popitem function.

0 commit comments

Comments
 (0)