Python Dictionary Operations and Examples
data = { "John": {"chinese": 77, "math": 66, "english": 33}, "Jay": {"chinese": 88, "math": 86, "english": 55}, "JJ": {"chinese": 99, "math": 96, "english": 66} }
score = data["John"]['chinese'] print(f"John's Chinese score is {score}")
2. Common Dictionary Operations
1) Add or Update Elements: dictionary[key] = value
2) Delete Elements: dictionary.pop(key)
3) Clear Dictionary: dicitonary.clear()
4) Get All Keys: dictionary.keys()
score = data.keys() print(score)
5) Iterate Through Dictionary:
Method 1: Get all keys and iterate
keys = data.keys() for key in keys: print(f"Dictionary key is: {key}")
Method 2: Iterate directly over the dictionary, each loop gives the key
for key in data: print(f"Dictionary key is: {key}") print(f"Dictionary value is: {data[key]}")
6) Count Elements in Dictionary: len()
3. Summary of Dictionaries
4. Exercises
dir = {"w": {"department": "tech", "salary": 3000, "level": 1}, "z": {"department": "marketing", "salary": 5000, "level": 2}, "l": {"department": "marketing", "salary": 7000, "level": 3}, "z": {"department": "tech", "salary": 4000, "level": 1}, "ld": {"department": "marketing", "salary": 6000, "level": 2}}
print(dir)
for key in dir: if dir[key]["level"] == 1: