Python - Dictionary

Python's dictionaries are kind of hash-table type. They work like associative arrays consist of key-value pairs. A dictionary key can be almost any Python type and should be unique and immutable

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example:

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values

dic.clear()
dic.get(1)
dic.pop()
print(dic.get(10))    # Do not give error if key not found
print(dic.get(10, 'Not Found'))

keys = ['amit', 'gagan', 'suraj']
values = ['c++', 'java', 'python']
data = dict(zip(keys,values))
data['priya'] = 'web'
del data['amit']
print (data)

This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])

Dictionaries have no concept of order among the elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.

Example 1: Input 3 student name, each student has 5 subjects marks and store in a dictionary

data = {}
for i in range(3):
    l = []
    n = input("Enter name")
    m1 = int(input("Enter 1st subject marks"))
    m2 = int(input("Enter 2nd subject marks"))
    m3 = int(input("Enter 3rd subject marks"))
    l.append(m1)
    l.append(m2)
    l.append(m3)
    data[n]=l
    print(data, "\n")