python - 循环查找两个字典中的匹配值
问题描述
我有两个不同的文件,其中包含字典。我试图仅遍历字典第一个文件中的键('name')、值并将它们与第二个文件匹配。我似乎得到了错误的输出,因为它循环通过两个键“名称”和“大小”。我已经研究了一些这样做的方法,但我不想能够将我的字典转换为集合。我希望能够打印出“匹配”或“不匹配”。到目前为止,我已经做了以下事情:
def compare_files():
with open('new.json', 'r') as current_data_file, open('old.json','r') as pre_data_file:
for current_data, previous_data in zip(current_data_file, pre_data_file):
data_current = json.loads(current_data)
data_previous = json.loads(previous_data)
for key, value in data_current.items():
if value not in data_previous:
print "No Match"
else:
print "Match"
这些是我正在加载的两个 json 文件:
旧的.json
{"name": "d.json", "size": 1000}
{"name": "c.json", "size": 1000}
{"name": "b.json", "size": 1000}
新的.json
{"name": "a.json", "size": 1000}
{"name": "b.json", "size": 1000}
{"name": "c.json", "size": 1000}
data_current 是:
{u'size': 1000, u'name': u'a.json'}
{u'size': 1000, u'name': u'b.json'}
{u'size': 1000, u'name': u'c.json'}
data_previous 是:
{u'size': 1000, u'name': u'd.json'}
{u'size': 1000, u'name': u'c.json'}
{u'size': 1000, u'name': u'b.json'}
输出 :
No Match
No Match
No Match
No Match
No Match
No Match
我的预期输出是:
No Match
Match
Match
b.json 和 c.json 都存在于两者中,但 a.json 和 d.json 不存在。
解决方案
为了避免麻烦,您可以使用 pandas(第三方库)直接读取数据,并且可以非常轻松地进行分析
import pandas as pd
df=pd.DataFrame('new.json')
df2=pd.DataFrame('old.json')
df.name.isin(df2.name).replace({False:'No Match',True:'Match'}).tolist()
输出
['No Match', 'Match', 'Match']