|
| 1 | +''' |
| 2 | +DICTIONARY |
| 3 | + Dictionaries are used to store key-value pairs which are mutable, or changeable, and ordered. |
| 4 | +''' |
| 5 | + |
| 6 | +#empty dictionary |
| 7 | +dict = {} |
| 8 | +print("This is an empty Dictionary ", dict, end="\n\n") |
| 9 | + |
| 10 | +#dictionary with elements |
| 11 | +dict = { |
| 12 | + 1: 'Python', 'Two': 'Java', 3: 'Swift', |
| 13 | + } |
| 14 | +print("Elements of dictionary are \n", dict, end="\n\n") |
| 15 | + |
| 16 | + |
| 17 | +''' Adding Elements ''' |
| 18 | + |
| 19 | +print("**********Adding Elements**********") |
| 20 | + |
| 21 | +#changing element |
| 22 | +dict[3] = 'C++' |
| 23 | +print(f"Changed 3rd element \n {dict}", end="\n\n") |
| 24 | + |
| 25 | +#adding key-value pair |
| 26 | +dict['Fourth'] = 'Swift' |
| 27 | +print("Added element \n", dict, end="\n\n") |
| 28 | + |
| 29 | + |
| 30 | +''' Accessing Elements ''' |
| 31 | + |
| 32 | +print("**********Accessing Elements**********") |
| 33 | + |
| 34 | +#access elements using keys |
| 35 | +print("First element is ", dict[1], end="\n\n") |
| 36 | +print("Fourth Element is ", dict.get('Fourth'), end="\n\n") |
| 37 | + |
| 38 | +#get keys |
| 39 | +print(f"Keys of the dictionary are \n{dict.keys()}", end="\n\n") |
| 40 | + |
| 41 | +#get values |
| 42 | +print(f"Values of the dictionary are \n{dict.values()}", end="\n\n") |
| 43 | + |
| 44 | +#get key-value pairs |
| 45 | +print(f"Dictionary is \n{dict.items()}", end="\n\n") |
| 46 | + |
| 47 | + |
| 48 | +''' Deleting Elements ''' |
| 49 | + |
| 50 | +print("**********Deleting Elements**********") |
| 51 | + |
| 52 | +#pop element |
| 53 | +a = dict.pop('Fourth') |
| 54 | +print(f"Deleted {a} \nNew dictionary {dict}", end="\n\n") |
| 55 | + |
| 56 | +#pop the key-value pair |
| 57 | +b = dict.popitem() |
| 58 | +print(f"Popped {b} \nNew dictionary {dict}", end="\n\n") |
| 59 | + |
| 60 | +#empty dictionary |
| 61 | +dict.clear() |
| 62 | +print(f"Cleared dictionary {dict}", end="\n\n") |
| 63 | + |
0 commit comments