Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Dictionary view objects

The objects returned by dict.keys(), dict.values() and dict.items() are view objects.
They provide a dynamic view on the dictionary’s entries, which means that when
the dictionary changes, the view reflects these changes.

Example of creating key view object


courses_dict={'python':4000,'java':2000,'oracle':1000}
courses=courses_dict.keys()
print(courses_dict)
print(courses)
for course in courses_dict:
print(course)

courses_dict['.net']=3000 # adding item within dictionary


print(courses_dict)
print(courses)

Output:
{'python': 4000, 'java': 2000, 'oracle': 1000}
dict_keys(['python', 'java', 'oracle'])
python
java
oracle
{'python': 4000, 'java': 2000, 'oracle': 1000, '.net': 3000}
dict_keys(['python', 'java', 'oracle', '.net'])
Example of creating values view object

sales_dict={2018:50000,2019:90000,2020:75000}
sales=sales_dict.values()
print(sales)
for sale in sales:
print(sale)

sales_dict[2017]=65000
print(sales)

Output:
dict_values([50000, 90000, 75000])
50000
90000
75000
dict_values([50000, 90000, 75000, 65000])
>>>

Example of creating items view object


dict1={1:'one',2:'two',3:'three',4:'four',5:'five'}
print(dict1)
d1=dict1.items() # creating items view object
print(d1)
for k,v in d1:
print(f'{k},{v}')

dict1[6]='six' # adding inside dictionary


print(d1)

Output:
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')])
1,one
2,two
3,three
4,four
5,five
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six')])
Dictionary is mutable collection, where we can add, update and delete items after
creation.

How to add items within dictionary?

Syntax:
dictionary-name[key]=value

This syntax is used to perform two operations.


1. Adding new item within dictionary
2. Updating the value of given key

If the key is not exists within dictionary, it will add key with given value
If the key is exists within dictionary, it will update value of given key.

Example of adding item within dictionary


>>> d1={}
>>> print(d1)
{}
>>> d1['one']=10
>>> d1['two']=20
>>> print(d1)
{'one': 10, 'two': 20}
>>> d1['three']=30
>>> print(d1)
{'one': 10, 'two': 20, 'three': 30}
>>>

https://www.hackerrank.com/challenges/finding-the-percentage/problem?
isFullScreen=true

marks={}
n=int(input())
for i in range(n):
l=input().split(" ")[:4]
marks[l[0]]=list(map(float,l[1:]))

name=input()
print(f'{sum(marks[name])/3:.2f}')

Example of adding items within dictionary during runtime


# write a program to add n sales persons sales
# each sales persons having name,sales

sales_dict={}
n=int(input("Enter how many sales person"))
for i in range(n):
name=input("Enter Name:")
sales=float(input("Enter sales:"))
sales_dict[name]=sales

for name,sales in sales_dict.items():


print(f'{name},{sales}')

total_sales=sum(list(sales_dict.values()))
print(f'Total sales {total_sales}')

Output:
Enter how many sales person2
Enter Name:naresh
Enter sales:9000
Enter Name:suresh
Enter sales:100000
naresh,9000.0
suresh,100000.0
Total sales 109000.0
>>>

How to update value?


Keys are immutable, after creating dictionary we cannot replace key but we can
replace value.

dictionary-name[key]=value

Example:
>>> d1={}
>>> d1[1]=100
>>> d1[2]=200
>>> d1[3]=300
>>> print(d1)
{1: 100, 2: 200, 3: 300}
>>> d1[1]=1000
>>> print(d1)
{1: 1000, 2: 200, 3: 300}
>>> d1[3]=99999
>>> print(d1)
{1: 1000, 2: 200, 3: 99999}
>>> d1[4]=8999
>>> print(d1)
{1: 1000, 2: 200, 3: 99999, 4: 8999}
>>>

Application which performs adding, updating and reading


XYZ Company
1. Signup
2. Signin  Change password
3. Exit
Enter your option:

users_dict={}
while True:
print("1. SignUp")
print("2. SignIn")
print("3. Exit")
opt=int(input("Enter option:"))
if opt==1:
name=input("UserName :")
if name in users_dict:
print(f'{name} is exists')
else:
users_dict[name]=input("Password:")
elif opt==2:
name=input("UserName :")
if name in users_dict:
pwd=input("Password")
if users_dict[name]==pwd:
print(f'{name}, welcome')
npwd=input("NewPassword:")
users_dict[name]=npwd
print("password updated...")
print("pls signin new password")
else:
print("invalid password")
else:
print("invalid user name")
elif opt==3:
break

How to delete items from dictionary?


del keyword
del keyword is used to delete item from dictionary

Syntax: del dictionary-name[key]

You might also like