0

I have a list and a dictionary . I need to pick the values from the list and find in dictionary and get the value of that key.if the key is present in dictonary return the value of the key

input_key= ['d0_f1','d1_f1','d1_f2','d3_f1']


dict = { 
                      "d0" : 
                     {
                       "d0_f1":"d0_v1",
                       "d3_f1" :"d3_v1"
                     },
                     "d1" : 
                     {
                       "d1_f1":"d1_v1",
                       "d1_f2" :"d1_v2"
                     }
            }

for key in input_key:
    key_value = key    
    for key in dict:
        if key == key_value:
        value1 = dict[key]
        print(value1)
vartika
  • 57
  • 1
  • 10

2 Answers2

0

Alert:

Don't use bult-in function as variables.

dict -- NO NO!

Check this,

>>> for i in input_key:
        for k in dict1.keys():
            if i in dict1[k].keys():
                print(dict1[k][i])

Output:

d0_v1
d1_v1
d1_v2
d3_v1
shaik moeed
  • 5,300
  • 1
  • 18
  • 54
0

As @shaik-moeed mentioned, don't use dict as a variable name. I'll call it just d. If d is big and the input list is long, then it's a pain to loop through the dict every time. We could instead build a new dict of just keys to values. Then it would be easy to query that for the input keys.

d2 =  {}
for sub_dict in d.values():
    d2.update(sub_dict)

Now just query d2 for the input_key.

for ik in input_key:
    if ik in d2:
        print(d2[ik])
blueteeth
  • 3,330
  • 1
  • 13
  • 23
  • The time complexity of this is `len(d) + len(input_key) ~= 1`. The time complexity of the other answer is `len(d) * len(input_key)`. – blueteeth Jul 06 '19 at 11:03