- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Dictionary / of Python Dictionary In-Built Functions Examples
# how to clear all elements in dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} student.clear() print(student)
# How to copy a dictionary? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} student2 = student.copy() print(student2)
# How to creat dictionary using keys and values keys = ("name", "age", "subjects") value = 1 student = dict() newDict = student.fromkeys(keys,value) print(newDict)
# What is the use of get method in dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} print(student["nae"]) # result = student.get("nae") result = student.get("ddd","1") print(result)
# How to get all itams from dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} items = student.items() print(items) for item in student.items(): print(item[1])
# How to get all keys from dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} keys = student.keys() print(keys) for key in keys: print(key)
# How to remove get random element in dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"], "roll":8} result = student.popitem() print('pop item',result) print(student)
# How to set default value if key not available student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} print(student["rank"]) student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} print(student) result = student.setdefault("ranks") print(student)
# How to remove element based on key in dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} result = student.pop("marks") print(result)
# How to get all values from dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} result = student.values() print(result) for value in student.values(): print(value)
# How to update the dictionaries in dict? student = {"name":"ram","marks":[200, 300, 250], "subjects":["maths", "physics", "chemisrty", "social"]} student2 = {"name":"krish","marks":[233, 333, 222], "rank":2} student.update(student2) print(student)