如何使用字符串列表在字典中搜索项目?

How to search items in dictionary using list of strings?

我有一本名为 'd' 的字典,其中包含键和值。我有另一个字符串列表,我必须从名为 list_to_find 的字典中查找值。这是我的代码。

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) 

我收到的错误是 AttributeError: 'str' object has no attribute 'get'

我的字典是这样的 我的 list_to_find 也是这样。

我的预期结果将包含匹配的单词及其值- ObtainedData : {'1st':'first','4th':'fourth'...} 我应该如何解决这个问题?请帮忙!! 我尝试使用此 link

来实现

但是,我无法得到结果并理解错误。

您的 'listOfValues' 是一个列表,当使用 for 循环对其进行迭代时,'ld' 已经包含该值。
ld.get() 在字符串上被调用,即 list_to_find 的值。

因此出现错误 AttributeError: 'str' object has no attribute 'get'

根据您在此发布的内容,并不完全清楚您想要做什么。

下面的这段代码将您的第一个字典(名为 d)中的值分配给用作新字典中键的列表元素。所有列表元素都必须包含在 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'}