Skip to content

Commit a2af96f

Browse files
committed
Add dictionary.py to demonstrate dictionary operations and manipulations in Python
1 parent 2fb7803 commit a2af96f

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Dictionary/dictionary.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Create a dictionary
2+
chai_types = {"Masala": "spicy", "ginger": "zesty", "Green": "Mild"}
3+
print(chai_types)
4+
5+
# Access values
6+
print(chai_types["Masala"]) # 'spicy'
7+
print(chai_types.get("ginger")) # 'zesty'
8+
print(chai_types.get("Gingery")) # None (not in dictionary)
9+
10+
# Update value
11+
chai_types["Green"] = "Fresh"
12+
print("Updated 'Green':", chai_types)
13+
14+
# Loop over keys
15+
for chai in chai_types:
16+
print("Key:", chai)
17+
18+
# Loop over keys with values
19+
for chai in chai_types:
20+
print("Key-Value:", chai, chai_types[chai])
21+
22+
# Loop using .items()
23+
for key, value in chai_types.items():
24+
print("With .items():", key, value)
25+
26+
# Membership test
27+
if "Masala" in chai_types:
28+
print("I have masala tea")
29+
30+
# Length
31+
print("Length:", len(chai_types))
32+
33+
# Add new key-value pair
34+
chai_types["Earl Grey"] = "Citrus"
35+
print("Added 'Earl Grey':", chai_types)
36+
37+
# Remove key
38+
chai_types.pop("ginger")
39+
40+
# Remove last inserted item
41+
chai_types.popitem()
42+
43+
# Delete key
44+
del chai_types["Green"]
45+
46+
# Copy dictionary
47+
chai_types_copy = chai_types.copy()
48+
print("Copied dict:", chai_types_copy)
49+
50+
# Nested dictionary
51+
tea_shop = {
52+
"chai": {
53+
"Masala": "Spicy",
54+
"Ginger": "zesty"
55+
},
56+
"Tea": {
57+
"Green": "Mild",
58+
"Black": "strong"
59+
}
60+
}
61+
print("Nested dict:", tea_shop)
62+
print("chai category:", tea_shop["chai"])
63+
print("Ginger tea:", tea_shop["chai"]["Ginger"])
64+
65+
# Dictionary comprehension
66+
squard_num = {x: x**2 for x in range(6)}
67+
print("Squared numbers:", squard_num)
68+
69+
# Creating a dictionary from keys with default value
70+
keys = ["Masala", "Ginger", "Lemon"]
71+
default_value = "Delicious"
72+
new_dict = dict.fromkeys(keys, default_value)
73+
print("New dict with default values:", new_dict)
74+
``

0 commit comments

Comments
 (0)