<h2>错误原因-</h2>
<p>python中的Dictionary没有<code>append()</code>方法,因此您将得到类似这样的错误-</p>
<blockquote>
<p><code><module>AttributeError: 'dict' object has no attribute 'append'> </code></p>
</blockquote>
<p>因此,append方法不能与dictionary一起添加新的key:value对。因此,您必须按照我在下面代码中显示的方式使用它</p>
<hr/>
<h2>正确的解决方案-</h2>
<p>当您找到匹配的键时,您必须迭代字典中的键并附加键的值。您应该按照以下方式进行操作-</p>
<pre><code>allJobs = {'A':[1,2,3],
'B':[2,3,4],
'C':[1,3],
'D':[3,4]}
Jobs = ['A','C']
JobsWithNums = {}
matchJobs =[]
for jobs in allJobs.keys():
if jobs in Jobs:
JobsWithNums[jobs] = allJobs[jobs]
# ^ : Adding the value corresponding to jobs when jobs is present in Jobs list
# You were trying to do with append which is not the valid way to add a key to dictionary
print(JobsWithNums)
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>{'A': [1, 2, 3], 'C': [1, 3]}
</code></pre>
<p>请注意,append方法不适用于dictionary。所以你必须像我在代码中那样使用它。您也可以使用<a href="https://docs.python.org/library/stdtypes.html#dict.update" rel="nofollow noreferrer">^{<cd2>}</a>方法来完成。请参阅以下片段-</p>
<pre><code>for jobs in allJobs.keys():
if jobs in Jobs:
JobsWithNums.update({jobs:allJobs[jobs]})
# Another possible variant =>
# JobsWithNums.update(jobs=allJobs[jobs])
</code></pre>
<p>但与第一种方法相比,这可能是一种效率低下的方法。仅当您必须同时将多个键更新到字典中时才使用它</p>
<hr/>
<h2>另一种方法-</h2>
<p>一种较短(pythonic)的方法如下=></p>
<pre><code>allJobs = {'A':[1,2,3],'B':[2,3,4],'C':[1,3],'D':[3,4]}
Jobs = ['A','C']
# The below code just says, add job_name:value pair if job_name exists in Jobs list
JobsWithNums = {job_name: value for job_name, value in allJobs.items()
if job_name in Jobs}
print(JobsWithNums)
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>{'A': [1, 2, 3], 'C': [1, 3]}
</code></pre>
<p>您可以在此处了解有关这些的更多信息-<a href="https://docs.python.org/3.4/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">python docs</a></p>
<p>希望这有帮助</p>