首页 > 解决方案 > 将值从列表传递到 dict.get() python

问题描述

我有一个包含 3 个值的列表。我希望我的循环能够遍历每个列表值并在 dict.get() 中使用,而不是为列表中的每个值输出相同的值。我知道这是在我的 for 循环中发生的,但不是对列表中的每个项目使用相同的值(使用 a.json 中的当前值和以前的值用于 b.json 和 c.json )我想要项目使用它们自己的对应值。我添加了如下代码:

def readFileIntoDict(pathOfFile):
    fo = open(pathOfFile, "rw+")
    linesOfFiles = fo.readlines()
    dataInFile = {}
    for line in linesOfFiles:
        jsonD = json.loads(line)
        dataInFile[jsonD['File Name']] = jsonD['File Size']
    return dataInFile

jsonDataprevFile = readFileIntoDict('dates/2018-01-01.json')
jsonDatacurrFile = readFileIntoDict('dates/2018-01-02.json')
list1 = jsonDataprevFile.keys()
list2 = jsonDatacurrFile.keys()
names_in_both = set(list1).intersection(list2)

# At this point it loops through 3 times 
file_names = ['a.json', 'b.json', 'c.json']


for fileNames in file_names:
    if fileNames in names_in_both:

         # Get the key a.json from file_name
         print(compare(jsonDataprevFile.get(file_names[0]), jsonDatacurrFile.get(file_names[0])))

标签: pythonjsonpython-2.7dictionary

解决方案


如果我做对了你想做的事情并假设compare()在代码的其他地方定义

for file_name in file_names:
    if file_name in names_in_both:
        # Get the key file_name from both json objects
        print(compare(jsonDataprevFile.get(file_name), jsonDatacurrFile.get(file_name)))

另外,请注意您的readFileIntoDict()函数看起来有点奇怪 - 如果输入的 json 文件确实是有效的 json,则不应逐行读取/解析。您可以上传示例输入 json 文件吗?


推荐阅读