Professional Documents
Culture Documents
Dictionary View Objects: Dict - Keys Dict - Values Dict - Items
Dictionary View Objects: Dict - Keys Dict - Values Dict - Items
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.
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])
>>>
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.
Syntax:
dictionary-name[key]=value
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.
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}')
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
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
>>>
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}
>>>
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