【问题标题】:Merge multiple python dictionaries into dynamic file将多个python字典合并到动态文件中
【发布时间】:2017-07-18 14:05:33
【问题描述】:

我想创建一个文件,将多个关于沿海天气条件(潮汐、风等​​)的 python 字典组合在一起,可以每天更新。数据来自多个 API 和网站,我将每个 API 和网站都转换为 Python 字典,并使用以下代码行合并到单个字典中:

OneDayWeather_data = {'Willydata' : Willydata, 'Bureau of Meteorology' : BoMdata, 'WeatherZone' : WZdata}

我的目标是每天对网站进行抽样;并使用网站上每天的天气和预报更新单个文件。我认为最好的方法是使用日期为层次结构创建一个新的顶层。所以它会像这样:

Weather_data['18/07/2017']['Willy']['Winds']

Weather_data['18/07/2017']['BoMdata']['Winds']

对于每一天,我都会为新一天的数据添加一个新的顶级条目,即

AllWeatherData['19/07/2017']['Willy']['Winds']

我已经尝试过使用堆栈溢出建议的各种方法(完全披露:我对 Python 很陌生)。例如,

# write the initial file
with open('test.json', 'w') as f:
    json.dump(OneDayWeather_data, f)    

# open the initial file and attempt to append
with open('test.json','r+') as f:
    dic = dict(json.load(f))
    dic.update(OneDayWeather_data)
    json.dump(dic, f)

# reopen the appended file
with open('test.json', 'r') as f2:
    json_object = json.load(f2)

...但是当我尝试重新打开时,我不断收到错误(在这种情况下:ValueError(errmsg("Extra data", s, end, len(s))))。希望有一些专业知识的人可以权衡如何解决这个问题。

谢谢!

【问题讨论】:

标签: python json dictionary


【解决方案1】:

您实际上是将更新字典附加到现有字典

# write the initial file
import json

OneDayWeather_data = {'a':'b'}

with open('test.json', 'w') as f:
    json.dump(OneDayWeather_data, f)

OneDayWeather_data = {'c':'d'}

# open the initial file and attempt to append
with open('test.json','r+') as f:
    dic = dict(json.load(f))
    dic.update(OneDayWeather_data)
    json.dump(dic, f)

# reopen the appended file
with open('test.json', 'r') as f2:
    json_object = json.load(f2)

在这个阶段,你的 test.json 看起来像

{"a": "b"}{"a": "b", "c": "d"}

你可以分开读/更新/写

with open('test.json','r') as f:
    dic = dict(json.load(f))
    dic.update(OneDayWeather_data)
with open('test.json', 'w') as f:
    json.dump(dic, f)

类似的答案可以在How to append in a json file in Python?找到

【讨论】:

  • 谢谢!完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 2022-11-14
  • 1970-01-01
  • 2017-01-04
  • 2019-09-18
  • 2020-12-24
  • 2017-09-15
相关资源
最近更新 更多