A Python dictionary is a collection of key-value pairs where each key is associated with a value. dictionary are used to store multiple items in a single variable. To separate two items, you use a comma ( , ) . A dictionary is like a list except that it uses parentheses { key : value } .
This program demonstrates the usage of dictionaries in Python. A dictionary is a collection of key-value pairs, where each key is unique. Initially, a dictionary 'user' is created with key-value pairs of user's name, age, and marital status.
Another dictionary 'users' is created that contains two dictionaries - 'user1' and 'user2' - as its values.
user = { "name": "Ram", "age": 25, "isMarried": True } print(user) print(type(user)) print(user["name"]) print(user.get('age')) print(user.keys()) print(user.values()) print(user.items()) for x in user: print(x," ",user[x]) for x in user.values(): print(x) for x in user.keys(): print(x) for x,y in user.items(): print(x,y) if "gender" in user: print("Present") # Changing Values user.update({"gender":"male"}) print(user) user["age"]=35 print(user) user.pop("age") print(user) user.clear() print(user) users={ "user1": { "name": "Ram", "age": 25, "isMarried": True }, "user2": { "name": "SAm", "age": 35, "isMarried": False } } print(users) for user in users: print(user["name"])To download raw file Click Here
{'name': 'Ram', 'age': 25, 'isMarried': True} <class 'dict'> Ram 25 dict_keys(['name', 'age', 'isMarried']) dict_values(['Ram', 25, True]) dict_items([('name', 'Ram'), ('age', 25), ('isMarried', True)]) name Ram age 25 isMarried True Ram 25 True name age isMarried name Ram age 25 isMarried True {'name': 'Ram', 'age': 25, 'isMarried': True, 'gender': 'male'} {'name': 'Ram', 'age': 35, 'isMarried': True, 'gender': 'male'} {'name': 'Ram', 'isMarried': True, 'gender': 'male'} {} {'user1': {'name': 'Ram', 'age': 25, 'isMarried': True}, 'user2': {'name': 'SAm', 'age': 35, 'isMarried': False}}
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions