Dict值未按排序顺序显示

2024-09-30 16:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个for循环,循环遍历两个json文件中的值并比较它们。当我打印出这些值时,我正在检查键“File Name”在两个文件之间是否匹配。数据顺序已交换,但值相同。他们没有改变。你知道吗

dave.json has a match 

emhy.json has no match 

same.json has no match 

我曾尝试使用sorted()按升序打印出来,但似乎仍然不起作用。我的JSON文件如下:

day.json
{"File Name": "dave.json", "File Size": 2800}
{"File Name": "same.json", "File Size": 600}
{"File Name": "emhy.json", "File Size": 600}

night.json 
{"File Name": "dave.json", "File Size": 2800}
{"File Name": "emhy.json", "File Size": 600}
{"File Name": "same.json", "File Size": 600}

值的顺序仍然相同。我的代码如下:

def compare_files():

    with open('day.json', 'r') as current_data_file, open('night.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)
        sorted_previous = sorted(data_previous.items() , key = lambda t: t[0])
        sorted_current = sorted(data_current.items(), key=lambda t: t[0])
        current_fn = data_current['File Name']
        previous_fn = data_previous['File Name']



        if sorted_previous == sorted_current:

            print (str(sorted_previous) + " has a match \n")

        elif sorted_previous != sorted_current:

            print (str(sorted_previous) + " has no match \n")





result = compare_files()

Tags: 文件nonamejsondatasizematchcurrent
1条回答
网友
1楼 · 发布于 2024-09-30 16:23:49

第一个问题-你的日期.json以及夜晚.json不是json文件,即使名称表明它们是。你知道吗

由于第一个问题,您无法直接加载它们。您可以按键分别加载和排序每一行,并与另一个文件中的相应行进行比较“文件名”总是在“文件大小”之前。如果顺序不同夜晚.json以及日期.json文件你来与不正确的结果。你知道吗

第三个问题是在新数据中查找文件,而不是在旧数据中查找。如果旧文件中有文件,而新文件中缺少该怎么办?你知道吗

如果文件是这种格式的,我会这样做

你知道吗日期.json你知道吗

{"File Name": "dave.json", "File Size": 2800}
{"File Name": "same.json", "File Size": 600}
{"File Name": "emhy.json", "File Size": 600}
{"File Name": "john.json", "File Size": 600}

你知道吗夜晚.json你知道吗

{"File Name": "jane.json", "File Size": 2800}
{"File Name": "dave.json", "File Size": 2800}
{"File Name": "emhy.json", "File Size": 600}
{"File Name": "same.json", "File Size": 600}

python代码

import json

def parse_file(file_name):
    with open(file_name) as f:
        return [json.loads(line)['File Name'] for line in f]

new_data = set(parse_file('day.json'))
old_data = set(parse_file('night.json'))

files_both = new_data.intersection(old_data) # files present in both
files_only_old = old_data.difference(new_data) # files in old, but not in new
files_only_new = new_data.difference(old_data) # files in new, but not in old

print(files_both) # {'emhy.json', 'dave.json', 'same.json'}
print(files_only_old) # {'jane.json'}
print(files_only_new) # {'john.json'}

输出

{'emhy.json', 'dave.json', 'same.json'}
{'jane.json'}
{'john.json'}

相关问题 更多 >