Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hygull/630f8d2f439f77cb66d36ac3ad4f64e3 to your computer and use it in GitHub Desktop.
Save hygull/630f8d2f439f77cb66d36ac3ad4f64e3 to your computer and use it in GitHub Desktop.
Creating a list of values from dictionary after checking if key is present in list or not created by hygull - https://repl.it/EmfJ/0
"""
{
"cretaed_after" : "Sun Dec 11 00:41:43 IST 2016"
"aim_of_program" : "checking whether the given key is present in the dictionary or not"
"If it is, then we have to insert the corresponding value into one list"
"Keys can be in any order"
"coded_by" : "Rishikesh Agrawani"
}
"""
def get_values_list_if_key_exists_in_list(d,l): #d is a dictionary and l is a list
ks=[]
print "Got => Dictionary as ",d," and list of keys as ",l
for key in l:
if key in d.keys():
ks.append( d[key] )
return ks
""" Start """
i1,j1,i2,j2,i3,j3 = 10,20,30,40,50,60 #(i1,j1) = (10,20), (i2,j2) = (30,40), (i3,j3) = (50,60)
n1,n2,n3 = 70,80,90 #n1=70, n2=80, n3=80
#1st test case...All keys are OK
f1 = {(i1,j1):n1, (i3,j3):n3, (i2,j2):n2}; #Dictionary
ks = [(i1,j1), (i2,j2), (i3,j3)]; #List of tuples
ns = get_values_list_if_key_exists_in_list(f1,ks)
print ns
#2nd test case...All keys are OK
f1 = {(i1,j1):n1,(i2,j2):n2,(i3,j3):n3};
ks = [(i2,j2), (i3,j3),(i1,j1)];
ns = get_values_list_if_key_exists_in_list(f1,ks)
print ns
#3rd test case...All keys are OK
f1 = {(i3,j3):n3,(i2,j2):n2 , (i1,j1):n1};
ks = [(i3,j3),(i2,j2),(i1,j1)];
ns = get_values_list_if_key_exists_in_list(f1,ks)
print ns
#4th test case...3rd key of list is not in the dictionary
f1 = {(i3,j3):n3,(i2,j2):n2 , (i1,j1):n1};
ks = [(i3,j3),(i2,j2),(i1,j3)];
ns = get_values_list_if_key_exists_in_list(f1,ks)
print ns
#4th test case...2rd and 3rd keys of list are not in the dictionary
f1 = {(i3,j3):n3,(i2,j1):n2 , (i1,j1):n1};
ks = [(i3,j3),(i2,j2),(i1,j3)];
ns = get_values_list_if_key_exists_in_list(f1,ks)
print ns
"""
Got => Dictionary as {(10, 20): 70, (30, 40): 80, (50, 60): 90} and list of keys as [(10, 20), (30, 40), (50, 60)]
[70, 80, 90]
Got => Dictionary as {(50, 60): 90, (10, 20): 70, (30, 40): 80} and list of keys as [(30, 40), (50, 60), (10, 20)]
[80, 90, 70]
Got => Dictionary as {(10, 20): 70, (50, 60): 90, (30, 40): 80} and list of keys as [(50, 60), (30, 40), (10, 20)]
[90, 80, 70]
Got => Dictionary as {(10, 20): 70, (50, 60): 90, (30, 40): 80} and list of keys as [(50, 60), (30, 40), (10, 60)]
[90, 80]
Got => Dictionary as {(30, 20): 80, (50, 60): 90, (10, 20): 70} and list of keys as [(50, 60), (30, 40), (10, 60)]
[90]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment