1#Creating dictionaries
2dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
3dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
4
5#Creating new pairs and updating old ones
6dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
7dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}
8
9#Accessing values through keys
10print(dict1['shape'])
11
12#You can also use get, which doesn't cause an exception when the key is not found
13dict1.get('false_key') #returns None
14dict1.get('false_key', "key not found") #returns the custom message that you wrote
15
16#Deleting pairs
17dict1.pop('volume')
18
19#Merging two dictionaries
20dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
21dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
22
23#Getting only the values, keys or both (can be used in loops)
24dict1.values() #dict_values(['red', 'square', 25, 4, 20])
25dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
26dict1.items()
27#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
1stationary_items = {
2 "Pencil":"Pencil is used to write things in copy",
3 "Eraser": "Eraser is used to remove the written things",
4 "Sharpner":"This is used to sharp your pencil"
5}
6print(stationary_items["Pencil"])
1#Creating dictionaries
2dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
3dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
1person = {}
2
3# Using get() results in None
4print('Salary: ', person.get('salary'))
5
6# Using [] results in KeyError
7print(person['salary'])
1Dictionary with the use of Integer Keys:
2{1: 'Geeks', 2: 'For', 3: 'Geeks'}
3
4Dictionary with the use of Mixed Keys:
5{1: [1, 2, 3, 4], 'Name': 'Geeks'}
6
7
1# Dictionaries are usually used to assign keywords to data.
2
3# Example, creating a player dictionary and manipulating it
4player_stat = {
5 'name': None,
6 'health': 100,
7 'inventory': ['Sword', 'Compass']
8}
9
10name = input('Enter your name: ')
11player_stat['name'] = name # adds the user's name to the dictionary
12player_stat['name'] = None # removes the name from the dictionary
13print(player_stat['health']) # prints a value from the dictionary
14# using the keyword 'health' >>> Output: 100
15
16# Loops through each piece of data in player_stat and outputs it
17# NOTE: 'i' is the keyword assigned to the data, and we put 'str()'
18# because health is an integer.
19for i in player_stat:
20 print(i + ": " + str(player_stat[i]))