简体   繁体   English

遍历 python 字典并从列表中返回匹配值

[英]Iterate through python dictionary and return matching value from list

I am having a hard time to get this code running and hope to get help from everyone.我很难让这段代码运行起来,希望能得到大家的帮助。 I have a dictionary and a list that i need to iterate through the list and return the dictionary with matching value.我有一个字典和一个列表,我需要遍历列表并返回具有匹配值的字典。 Here is the code I have so far and the desire output that i can print out to excel as well这是我到目前为止的代码以及我也可以打印到 excel 的愿望 output

allJobs = {'A':[1,2,3],
           'B':[2,3,4],
           'C':[1,3],
           'D':[3,4]}

Jobs = ['A','C']

JobsWithNums = {}
matchJobs =[]


for jobs in allJobs:
    if jobs in Jobs:
        JobsWithNums.append(jobs)
        
print(JobsWithNums)
JobsWithNums = {'A':[1,2,3],
                'C':[1,3]}

Cause of Error -错误原因 -

Dictionary in python has no append() method and hence you would be getting an error something like this - python 中的字典没有append()方法,因此您会收到类似这样的错误 -

<module>AttributeError: 'dict' object has no attribute 'append'>

So, the append method does not work with dictionary for adding new key:value pairs.因此,append 方法不适用于添加新键:值对的字典。 So you have to use it the way I have shown in the code below.所以你必须按照我在下面的代码中显示的方式使用它。


Correct Solution -正确的解决方案 -

You have to iterate over the keys of dictionary and append the value of key when you find the matching key.当您找到匹配的键时,您必须遍历字典的键和 append 键的值。 You should be doing it as follows -你应该这样做 -

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)

Output: Output:

{'A': [1, 2, 3], 'C': [1, 3]}

Do note that the append method does not work with dictionary.请注意,append 方法不适用于字典。 So you have to use it the way I have done it in code.所以你必须像我在代码中那样使用它。 You could also do it usingdict.update() method.你也可以使用dict.update()方法来做到这一点。 Refer the following snippet -请参阅以下片段 -

for jobs in allJobs.keys():
    if jobs in Jobs:
        JobsWithNums.update({jobs:allJobs[jobs]})
       # Another possible variant =>
       # JobsWithNums.update(jobs=allJobs[jobs])

But this would probably be an inefficient way to do it as compared to the first one.但与第一种方法相比,这可能是一种低效的方法。 Use it only if you have to update multiple keys into dictionary at once.仅当您必须一次将多个键更新到字典中时才使用它。


Alternate way of doing it -另一种做法——

A shorter (pythonic) way of doing it would be as follows =>一种更短的(pythonic)方法如下=>

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)

Output: Output:

{'A': [1, 2, 3], 'C': [1, 3]}

You can learn more about these here - python docs您可以在此处了解有关这些的更多信息 - python 文档

Hope this helps !希望这可以帮助 !

You can try this:你可以试试这个:

for job in allJobs.keys():
    if job in Jobs:
        JobsWithNums[job] = alljobs[job]

The.key() here returns the names of the jobs (A, B, C, D) and you later reference it like alljobs to get the value.此处的.key() 返回作业的名称(A、B、C、D),稍后您可以像alljobs一样引用它来获取值。

The append method does not work the way you expect with dictionaries. append 方法无法按照您对字典的预期方式工作。 You can do the following in your loop to get around this:您可以在循环中执行以下操作来解决此问题:

for jobs, nums in allJobs.items():
    if jobs in Jobs:
        JobsWithNums[jobs] = nums

This is iterating over all of the keys and values in your dictionary and creating those entries in the new JobsWithNums dict.这是遍历字典中的所有键和值,并在新的 JobsWithNums 字典中创建这些条目。

Alternatively, you can build the same list in one line using dict comprehension:或者,您可以使用 dict 理解在一行中构建相同的列表:

JobsWithNums = {k:v for k,v in allJobs if k in Jobs}

You can do this fairly easily with a dictionary comprehension:您可以通过字典理解相当容易地做到这一点:

jobsWithNums = {job_name: value for job_name, value in allJobs.items()
                if job_name in Jobs}
print(jobsWithNums)

And the output is: output 是:

{'A': [1, 2, 3], 'C': [1, 3]}

A better way to do this is iterating through the list and if that element exists in the dictionary append it to JobsWithNums.更好的方法是遍历列表,如果该元素存在于字典 append 中,则将其传递给 JobsWithNums。 An advantage of this is you only need to iterate through the list once and the lookup time for the dictionary is O(1) so it will be more efficient.这样做的一个优点是您只需要遍历列表一次,并且字典的查找时间是 O(1),因此它会更有效。

JobsWithNums = {}
for job in Jobs:
    if allJobs.get(job):
        JobsWithNums[job] = allJobs[job]

get() on dictionary return None if key is not present如果键不存在,字典上的 get() 返回 None

Thank you for all the helps and I have been able to run it.感谢您的所有帮助,我已经能够运行它。 Also I am trying to export the result to excel using pandas data frame but not being able to do so and run into the error of arrays must all e same length - and how can i name the columns of the data frame as Jobs, Nums此外,我正在尝试使用 pandas 数据帧将结果导出到 excel 但无法这样做并遇到 arrays 的错误,该错误必须与列的 iframe 长度相同 - 以及如何

df = pd.DataFrame(JobsWithNums)
df.to_excel("file.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM