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
Also my list_to_find looks like this.
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.
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'}