簡體   English   中英

Python:在多個json文件中存儲字典

[英]Python: Storing a dictionary in more than one json file

我有一個這樣的字典:

{'ahik': [2, 1, 3, 1, 4, 1, 5, 1], 'tyeo': [5, 4, 3, 5, 3, 3, 2], 'abc': [1, 2, 3, 4, 5, 2, 1]....}

由於字典非常大,我想將它存儲在兩個json文件中,這兩個文件都有一部分字典(比方說50%)。 另外,一旦我存儲它,如何檢索它?

分裂詞典有多種方法。 這是一個。

from itertools import islice

spam = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5'}
spam1, spam2 = [dict(islice(spam.items(), i, None, 2)) for i in (None, 1)]
print(spam1, spam2)  # {'a': '1', 'c': '3', 'e': '5'} {'b': '2', 'd': '4'}

我們可以將項目轉換為元組並使用常規切片,但由於你的dict“非常大”,所以使用islice可能更好。

import json然后你可以使用json.dump()將dict保存到文件中,並使用json.load()從文件中獲取dict。

要合並這兩個dicts,請使用dict.update()

spam1.update(spam2)
print(spam1)  # {'a': '1', 'c': '3', 'e': '5', 'b': '2', 'd': '4'}

首先,您必須將字典轉換為鍵和值列表,然后將它們拆分並轉儲到兩個不同的文件中,

import json
d = {'ahik': [2, 1, 3, 1, 4, 1, 5, 1], 'tyeo': [5, 4, 3, 5, 3, 3, 2], 'abc': [1, 2, 3, 4, 5, 2, 1]}
dlist=list(d.items())
with open("firsthalf.txt","w") as df1, open("secondhalf.txt","w") as df2:
    json.dump(dict(dlist[:len(d)//2]),df1)
    json.dump(dict(dlist[len(d)//2:]),df2)

現在它將我們的字典存儲到兩個文件作為兩個半字典,現在從我們必須加載和合並這兩個字典的那兩個文件中檢索它們。

with open("firsthalf.txt","r") as df1, open("secondhalf.txt","r") as df2:
    fh,sh=json.load(df1),json.load(df2)
mydict = fh.copy()
mydict.update(sh)
print(mydict)

OUTPUT:

{'abc': [1, 2, 3, 4, 5, 2, 1], 'tyeo': [5, 4, 3, 5, 3, 3, 2], 'ahik': [2, 1, 3, 1, 4, 1, 5, 1]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM