python - 将值从列表传递到 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])))
解决方案
如果我做对了你想做的事情并假设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 文件吗?
推荐阅读
- android - 推送通知未显示在通知栏上
- c - openssl c api 给出 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY,而 openssl s_client 命令工作正常
- spring - 休眠多对一映射:引起:java.sql.SQLException:列名无效
- css - 让子主题的 Style.css 覆盖任何冲突的 CSS (WordPress/Masterstudy)
- r - 定义轴值 r
- css - 角度应用中的 ag-grid 2 行单元格换行
- stm32 - STM32L496产生方波的精度
- fullcalendar - Fullcalendar.io v5 - 如果一天有事件,则将类添加到日单元格
- python - 如何从 JSON 中获取值
- arraylist - 在地图中的所有值列表中查找值,如果找到则返回键。任何有效/更快的解决方案解决方案?