Python – Dictionary Basics with Programs

Dictionary

-> Key – Value Pair
-> No Duplicate keys allowed
-> Duplicate values are possible
-> Heterogeneous objects for both keys and values allowed
-> Insertion Order is not maintained
-> Dictionaries are mutable
-> Indexing and Slicing – not supported

Dictionary Creation:

d = {}
d = dict()
d[10] = ‘muthu’
d[200] = ‘kavin’

d = {10:’muthu’,200:’kavin’}

Accessing Data from Dictionary:

print(d[100])
print(d[2])

Program:

Enter name and % in Dictionary

register = {}
n = int(input(“Enter no “))
i = 1
while i<=n:
name = input()
perc = input()
register[name] = perc
i+=1

for x in register:
print(“\t”, x, “\t\t”, register[x])

Update Dictionaries:

d[key] = value
d = {100:’muthu’,200:’kavin’}
print(d)
d[300] = ‘viyan’
print(d)
d[100] = ‘navilan’
print(d)

Delete Elements from Dictionary

del d[key]

del d[100]

clear()

d.clear()

del d to delete total dictionary

Functions

1 dict()

d = dict([(100,’muthu’), (200,’muthu’)])

2 len()

3 clear()

4 get(key)

d.get(key)

print(d[100]) #muthu
இல்லாத keyஐக் கொடுத்தால்,
print(d[1000]) #keyerror

print(d.get(1000)) #None

5 pop(key)

removes the entry with the given key and returns the corresponding value

If key is not present, KeyError will be thrown.

popitem()

ஏதாவது ஒரு key-valueஐ நீக்கித் தரும்.

d = {100:”muthu”, 200:”Kavin”}
print(d)

print(d.popitem())
print(d)

7 keys()

d = {100:”muthu”, 200:”kavin”}
print(d.keys())
for k in d.keys():
print(k)

8 values()

print(d.values())
for v in d.values():
print(v)

9 items()

returns list of tuples representing key-value pairs
for k,v in d.items():
print(k,”–“, v)

for it in d.items():
print(it)
print(type(it))

for i in d:
print(i)

10 copy()

d2 = d.copy()

11 setdefault()

d.setdefault(k,v)
இங்கு key ஏற்கெனவே இருந்தால், function returns corresponding value. key இல்லை எனில் specified key-vaue, புது item ஆக dictionaryஇல் சேர்க்கப்படும்.

12 update()

d.update(x)
All items present in the dictionary will be added to dictionary d

13 get

d = {‘Name’:’Muthu’, ‘Age’: 50}
print(d.get(‘Age’))
print(d.get(‘Salary’))
print(d.get(‘Salary’,’Not available’))

Programs

Take dictionary from keyboard and print sum of values

d = eval(input(“Enter dictionary “))
s = sum(d.values())
print(s)

2 Number of occurrences of each letter

word = input(“Enter any word “)
d = {}
for x in word:
d[x] = d.get(x,0)+1

for k,v in d.items():
print(k, “occurrred “, v, ” times “)

3 Number of occurrences of each vowel

word = input(“Word “)
vowels = {‘a’,’e’,’i’,’o’,u’}
d = {}
for x in word:
if x in vowels:
d[x] = d.get(x,0)+1

for k,v in sorted(d.items()):
print(k,v)

4 Frequencey of each number

l = [1,1,2,3,5,2,5,7,8,10,7]
freq = {}
for no in ll:
if not no in freq:
freq[no] = 1
else:
freq[no] = freq[no]+1

for key, value in freq.items():
print(“%d : %d “%(key,value))

5

prices = {‘apple’:100, ‘banana’:40, ‘orange’: 60, ‘papaya’:30}

for name, price in prices.items():
price[name] = round(price * 1.1, 2)

print(price)

6

list = prices.keys()
for key in list:
if key == ‘orange’:
del prices[key]
break
print(price)

7 keyஐ value ஆகவும் valueஐ key ஆகவும் மாற்றுங்கள்.

employees = {‘kathir’:100, ‘kannan’: 200, ‘kumaran’: 300}
new_emp = {}
for name, id in employee.items():
new_emp[id] = name

print(new_emp)

employees = {value:key for key, value in employee.items()}

8

emp = {‘arul’:12345, ‘mathi’:23456, ‘chemmal’: 34567}

for name, salary in emp.items():
if salary >=10000:
print(name)

9

for name in sorted(emp):
print(name, ” : “, emp[name])

10

for salary in sorted(emp.values()):
print(salary)

11

total_income = 0
for key in sorted(emp):
print(key, ‘ : ‘, emp[key])
total_income += emp[key]

12

details = {‘name’: ‘Mukhil’, ‘age’: 21, ‘city’: ‘tirunelveli’}
print(‘tirunelveli’ in details.values())

13

n = int(input(“Enter no. of students “))
d = {}
for i in range(n):
name = input(“Enter name “)
marks = int(input(“Mark “))
d[name] = marks

while True:
name = input(“Enter student name “)
marks = d.get(name, -1)
if marks == -1:
print(‘Student not found’)
else:
print(name, marks)
option = input()
if option == ‘No’:
break