Skip to content

Commit ee2aa3c

Browse files
committed
Dictionary Scripts added
1 parent 158ea2c commit ee2aa3c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Dictionary.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Dictionary is a collection of key-value pairs
2+
# Mutable
3+
myDict = {
4+
"fast": "In a Quick Manner",
5+
"mahar": "A Coder",
6+
"marks": [1, 2, 5], # "fast, mahar, marks" are keys and their corresponding values are "In a Quick Manner, A Coder, [1, 2, 5]"
7+
"anotherdict": {'ronaldo': 'Player'} # Nested dictionary inside myDict
8+
}
9+
10+
print(myDict['fast']) # Access value by 'fast' key
11+
print(myDict['mahar']) # Access value by 'mahar' key
12+
13+
# Update the value of 'marks'
14+
myDict['marks'] = [45, 78]
15+
print(myDict['marks']) # Print the updated 'marks' value
16+
17+
# Access nested dictionary value using 'ronaldo' key inside 'anotherdict'
18+
print(myDict['anotherdict']['ronaldo'])
19+
20+
# Dictionary Methods
21+
print(myDict.keys()) # Display all keys in the dictionary
22+
print(myDict.values()) # Display all values in the dictionary
23+
print(type(myDict.keys())) # Display the data type of keys, which is 'dict_keys'
24+
print(list(myDict.keys())) # Convert keys to a list for easier manipulation
25+
print(myDict.items()) # Display key-value pairs in tuple form for all contents in the dictionary
26+
27+
# Update the dictionary by adding key-value pairs from updateDict
28+
updateDict = {"ck": "friend"}
29+
myDict.update(updateDict) #update the dictionary by adding key-value pairs from updateDict
30+
print(myDict)
31+
32+
# Difference between .get() and normal dictionary key access
33+
print(myDict.get("ck")) # Output will be 'friend'
34+
print(myDict.get("ck2")) # Output will be 'None', as 'ck2' key doesn't exist
35+
print(myDict["ck"]) # output will be 'friend'
36+
#print(myDict["ck2"]) # The following line will raise a KeyError as 'ck2' key doesn't exist
37+

0 commit comments

Comments
 (0)