Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Dictionary Operations and Examples

Tech May 15 1

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:

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.