我有两个不同的文件,其中包含字典。我试图仅循环遍历字典第一个文件中的键(“名称”)和值,并将它们与第二个文件进行匹配。当它循环遍历键“名称”和“大小”时,我似乎得到了错误的输出。我已经研究了几种执行此操作的方法,但我不希望能够将我的字典转换为集合。我希望能够打印出“匹配”或“不匹配”。到目前为止我已经做了以下工作:
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}
new.json
{"name": "a.json", "size": 1000}
{"name": "b.json", "size": 1000}
{"name": "c.json", "size": 1000}
当前数据是:
{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']
关于python - 循环在两个字典中查找匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745893/