|
| 1 | +user = { |
| 2 | + "name" : "john", |
| 3 | + "age": 40, |
| 4 | + "password": "pass123" |
| 5 | +} |
| 6 | + |
| 7 | +# copy() : Returns a copy of the dictionary |
| 8 | +user_copy = user.copy() |
| 9 | +print(user_copy) |
| 10 | + |
| 11 | +# clear() : Removes all the elements from the dictionary |
| 12 | +user_copy.clear() |
| 13 | +print(user_copy) |
| 14 | + |
| 15 | +# fromkeys() Returns a dictionary with the specified keys and value |
| 16 | +keys = ('name','age','password') |
| 17 | +val = None |
| 18 | + |
| 19 | +user_dict = dict.fromkeys(keys,val) |
| 20 | +print(user_dict) |
| 21 | + |
| 22 | +# or |
| 23 | + |
| 24 | +keys = ('name','age','password') |
| 25 | +user_dict = dict.fromkeys(keys) |
| 26 | +print(user_dict) |
| 27 | + |
| 28 | +# get() Returns the value of the specified key |
| 29 | +print(f"name : {user.get('name')}") |
| 30 | +print(f"age : {user.get('age')}") |
| 31 | + |
| 32 | + |
| 33 | +# items() Returns a list containing a tuple for each key value |
| 34 | +for key,val in user.items(): |
| 35 | + print(f"{key} : {val}") |
| 36 | + |
| 37 | + |
| 38 | +# keys() Returns a list containing the dictionary's keys |
| 39 | +print("printing all key") |
| 40 | +for key in user.keys(): |
| 41 | + print(key) |
| 42 | + |
| 43 | + |
| 44 | +# pop() Removes the element with the specified key |
| 45 | +print("using pop() : ") |
| 46 | +print(user_dict) |
| 47 | +user_dict.pop("age") |
| 48 | +print(user_dict) |
| 49 | + |
| 50 | + |
| 51 | +# popitem() Removes the last inserted key-value pair |
| 52 | +print("using popitem() : ") |
| 53 | +print(user_dict) |
| 54 | +user_dict.popitem() |
| 55 | +print(user_dict) |
| 56 | + |
| 57 | + |
| 58 | +# setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
| 59 | +user.setdefault("is_admin",False) |
| 60 | +print(user) |
| 61 | + |
| 62 | +# update() Updates the dictionary with the specified key-value pairs |
| 63 | +# uodate existing value |
| 64 | +user.update({"is_admin":True}) |
| 65 | +print(user) |
| 66 | +# help in adding new item |
| 67 | +user.update({"is_logged_in":True}) |
| 68 | +print(user) |
| 69 | + |
| 70 | + |
| 71 | +# values() Returns a list of all the values in the dictionary |
| 72 | + |
| 73 | +for val in user.values(): |
| 74 | + print(val) |
0 commit comments