我如何比较两个字典列表

时间:2018-12-28 08:23:20

标签: python

list1:


[
    {'id': 1, 'location': 'Mumbai', 'job_description': 'python'},
    {'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}
]


list2:

[
    {'preferred_location': 'Bengaluru', 'skills': 'python'},
    {'preferred_location': 'Hyderabad', 'skills': 'java'},
    {'preferred_location': 'Cochin', 'skills': 'angular'}
]

如何根据位置比较第一个列表和第二个列表。 第一个位置列表中的位置应与第二个列表中的首选位置相匹配。

预期的结果将是

        [
            {'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}
        ]

因为第一个列表的“位置”与第二个列表2的“ preferred_location”匹配 并且只会显示foo

4 个答案:

答案 0 :(得分:1)

您可以使用列表推导,将字典放在位置匹配的list1中:

r1 = range(len(list1))
r2 = range(len(list2))
[list1[j] for i in r2 for j in r1 if list1[j]['location'] ==
                                     list2[i]['preferred_location']]


[{'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}]

答案 1 :(得分:1)

让我们运用列表理解来解决这个问题。

list1 =[{'id': 1, 'location': 'Mumbai', 'job_description': 'python'},
    {'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}]


list2=[{'preferred_location': 'Bengaluru', 'skills': 'python'},
    {'preferred_location': 'Hyderabad', 'skills': 'java'},
    {'preferred_location': 'Cochin', 'skills': 'angular'}]

list2_locations= [i['preferred_location'] for i in list2]

list2_locations
     ['Bengaluru', 'Hyderabad', 'Cochin']

list1_final = [i for i in list1 if i['location'] in list2_locations]

list1_final
     [{'id': 2, 'job_description': 'software engineer', 'location': 'Bengaluru'}]

答案 2 :(得分:1)

您还可以使用大熊猫

df1 = pd.DataFrame(
[
{'id': 1, 'location': 'Mumbai', 'job_description': 'python'},
{'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}
]).set_index('location').reset_index()


df2 = pd.DataFrame(
[
{'preferred_location': 'Bengaluru', 'skills': 'python'},
{'preferred_location': 'Hyderabad', 'skills': 'java'},
{'preferred_location': 'Cochin', 'skills': 'angular'}
]).set_index('preferred_location').reset_index()


df3 = df2.merge(df1, how='inner', left_on='preferred_location', right_on='location')

del df3['location']

df3.to_dict('records')

答案 3 :(得分:1)

import pandas as pd

list1 = [{'id': 1, 'location': 'Mumbai', 'job_description': 'python'}, 
{'id': 2, 'location': 'Bengaluru', 'job_description': 'software engineer'}
]
list2 = [{'preferred_location': 'Bengaluru', 'skills': 'python'}, 
{'preferred_location': 'Hyderabad', 'skills': 'java'}, 
{'preferred_location': 'Cochin', 'skills': 'angular'}
]

df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)

df3 = df1.merge(df2, left_on='location', right_on='preferred_location', how='inner')


list_final = list(df3.T.to_dict().values())

print(list_final)

输出:

[{'id': 2, 'job_description': 'software engineer', 'location': 'Bengaluru', 'preferred_location': 'Bengaluru', 'skills': 'python'}]