-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ19.py
76 lines (67 loc) · 1.9 KB
/
Q19.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#Dictionary
info = {
"name" : "Ish",
"subjects" : ["Java", "Python"],
"topics" : ("Dictionary", "Sets"),
"learning" : "Python",
"age" : 21,
"is_adult" : True,
"marks" : 95
}
print(type(info))
print(info["age"])
info["name"] = "Isha"
info["surname"] = "Rani"
print(info)
# Output
# {'name': 'Ish', 'subjects': ['Java', 'Python'], 'topics': ('Dictionary', 'Sets'), 'learning': 'Python', 'age': 21, 'is_adult': True, 'marks': 95}
# <class 'dict'>
# 21
# {'name': 'Isha', 'subjects': ['Java', 'Python'], 'topics': ('Dictionary', 'Sets'), 'learning': 'Python', 'age': 21, 'is_adult': True, 'marks': 95, 'surname': 'Rani'}
#Nested Dictionary
student = {
"name" : "Rahul Kumar",
"subjects" : {
"phy" : 86,
"chem" : 88,
"maths" : 87
}
}
print(student)
print(student["subjects"])
print(student["subjects"]["chem"])
# Output
# {'name': 'Rahul Kumar', 'subjects': {'phy': 86, 'chem': 88, 'maths': 87}}
# {'phy': 86, 'chem': 88, 'maths': 87}
# 88
#Dictionary Methods
#.keys() - returns all keys
print(student.keys())
print(list(student.keys())) #typecast to list
print(len(list(student.keys())))
# Output
# dict_keys(['name', 'subjects'])
# ['name', 'subjects']
# 2
#.values() - returns all values
print(list(student.values()))
# Output
# ['Rahul Kumar', {'phy': 86, 'chem': 88, 'maths': 87}]
#.items() - returns all (key, value) pairs as tuples
print(list(student.items()))
pairs = list(student.items())
print(pairs[0])
# Output
# [('name', 'Rahul Kumar'), ('subjects', {'phy': 86, 'chem': 88, 'maths': 87})]
# ('name', 'Rahul Kumar')
#.get("key") - returns the key according to value
print(student["name"])
print(student.get("name"))
# Output
# Rahul Kumar
# Rahul Kumar
#.update() - inserts the specified items to the dictionary
student.update({"city" : "Ranchi"})
print(student)
# Output
# {'name': 'Rahul Kumar', 'subjects': {'phy': 86, 'chem': 88, 'maths': 87}, 'city': 'Ranchi'}