How to search items in dictionary using list of strings?

108 Views Asked by At

I have a dictionary with keys and values called 'd'. I have another list of strings that I have to find values from the dictionary called list_to_find. Here is my code.

def getKeysByValues(dictOfElements, listOfValues):
  p = {}
  for match in dictOfElements:
   for ld in listOfValues:
     p.setdefault(match, []).append(ld.get(match, 0))
  return  p

ObtainedData = getKeysByValues(d,list_to_find) 

The error I am getting is AttributeError: 'str' object has no attribute 'get'

My dictionary looks like this enter image description here Also my list_to_find looks like this. enter image description here

My expected result would contain matched words with its values- ObtainedData : {'1st':'first','4th':'fourth'....} How should I solve this? please help!! I have tried to implement using this link here

However, I am not being to able to get the result and understand the error.

2

There are 2 best solutions below

0
New2coding On BEST ANSWER

From what you posted in this not entirely clear what you want to do.

This code below assigns values from your first dictionary (named d) to the list elements that are used as keys in a new dictionary. All of the list elements must be contained within d.

import numpy as np

d = {
'1st': ['first'],
'4th': ['fourth'],
'c': [np.nan],
'd': [np.nan],
'e': [np.nan],
'f': [np.nan],
'g': [np.nan]
}

l = ['1st', '4th']

new_d = {}

for i in l:
  new_d[i] = ''.join(d[i])

print(new_d)
#{'1st': 'first', '4th': 'fourth'}
2
Pratham On

Your 'listOfValues' is a list and when iterating it using for loop the 'ld' already contains the value.
ld.get() is getting called on a string, i.e. the values of the list_to_find.

Hence the error AttributeError: 'str' object has no attribute 'get'