my_dict={'a':'Alex','b':'Ronald'}
if 'b' in my_dict:
print("Yes, it is there ")
else:
print("No, not there")
Output
Yes, it is there
Searching value by using values()
my_dict={'a':'Alex','b':'Ronald'}
if 'Ronald' in my_dict.values():
print("Yes, it is there ")
else:
print("No, not there")
Output is here
Yes, it is there
Getting Key by using Value of a dictionary
But this requirement is not for which dictionary is usually used. If possible then while creating the dictionary, key and value can be changed.
However here is the solution for getting key by using value.
my_dict={'a':'Alex','b':'Ronald'}
for i,j in my_dict.items():
if j=='Ronald':
print(i)
Output
b
When we use list as value of a dictionary, we can get other values by using any one element of the list. Here by using matching name we get the connected mark ( integer value inside list ) and the key.
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
# display the mark of the matching name along with id
for i,j in my_dict.items():
if j[0]=='Ronald':
print("Mark:",j[1], ", Key or id :",i)
Output
Mark: 40 , Key or id : b
Searching values for matching element
for i,j in my_dict.items():
if 'Ronn' in j:
print(i,">>",j)
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_tutorial")
query = "SELECT * FROM student LIMIT 0,5"
my_data = list(my_conn.execute(query)) # SQLAlchem engine result set
my_dict = {} # Create an empty dictionary
my_list = [] # Create an empty list
for row in my_data:
my_dict[[row][0][0]] = row # id as key
my_list.append(row[1]) # name as list
print(my_dict)
print(my_list)
# Print the other values for matching Name
for i, j in my_dict.items():
if j[1] == "Arnold":
print(i, j[0], j[1], j[2])
Question
Find out the frequency of occurrence of chars in a string?
my_str='Welcome to Python'
my_dict={}
for i in my_str:
if i in my_dict:
my_dict[i] = my_dict[i] + 1
else:
my_dict[i] = 1
print(my_dict)
Ask for Name and mark of three students
Create a dictionary with this and print them
Following details of the student are to be stored.
Name ( this will be key of the dictionary )
Mark in three subjects i.e Physics , Chemistry , Math
Attendance in number of days
Create a dictionary and store three student details as mentions above.
Print the dictionary
Display all students name and attendance
Create one csv( comma separated value ) file with id ( integer) , name(string), mark1(integer ), mark2(integer),mark3(integer), attendance(integer)
Read the file and using the data create one dictionary. The first column id of the csv file should be the key and rest of the data should be value of the dictionary.
One sample csv file is kept here with some data. Same can be used.