【问题标题】:How can i merge two different python dictionary into single one?如何将两个不同的 python 字典合并为一个字典?
【发布时间】:2020-07-09 08:15:09
【问题描述】:

我有两个 python 字典,我将写入一个 json 文件。

{“音频”:[{“fs”:“8000”,“持续时间”:“240”}]}

{“ref”:[{“end”:“115.63”,“start”:“111.33”},{“end”:“118.49”, “开始”:“117”}]}

我将它们合并如下;

dict={}
dict["audio"]=[{"fs":"8000", "duration": "240"}]
dict1={"audio":dict["audio"]}
dict["ref"]={"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
dict2={"ref":dict["ref"]}
dict={"audio":dict["audio"]}, {"ref":dict["ref"]}

当我写入一个 json 文件时,我得到如下输出;

with open("a.json", 'w') as fout:
    json.dump((dict), fout)

[{“音频”:[{“fs”:“8000”,“持续时间”:“240”}]},{强>“参考”:{“参考”: [{“结束”:“115.63”,“开始”:“111.33”},{“结束”:“118.49”,“开始”: "117"}]}}]

我想得到一个字典的输出;

我想要的输出:

{“音频”:[{“fs”:“8000”,“持续时间”:“240”}],“参考”:[{“开始”: “111.33”,“结束”:“115.63”},{“开始”:“117”,“结束”:“118.49”}, {“开始”:“119.31”,“结束”:“122.02”}]}

我用粗体写了上面两个输出之间的差异。 (还有额外的 "[ ]" 和 "{ }" )。

【问题讨论】:

    标签: python json dictionary formatting


    【解决方案1】:

    试试这个,

    import json
    
    audio = {"audio": [{"fs": "8000", "duration": "240"}]}
    ref = {"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
    
    json.dumps({**audio, **ref})
    

    Python 版本
    from collections import OrderedDict
    
    audio = {"audio": [{"fs": "8000", "duration": "240"}]}
    ref = {"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
    
    json.dumps(OrderedDict({**audio, **ref}))
    

    【讨论】:

    • 输出为{"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}], "audio": [{"fs": "8000", "duration": "240"}]}。 “ref”和“audio”字典改变了它们的位置。为什么会这样?我无法理解。
    • 从 python 3.6 dict 维护插入顺序,如果你使用较低版本,那么你将需要使用OrderedDict,refer this
    【解决方案2】:

    虽然我不确定您要做什么,但这可能会回答您的问题,请不要使用 dict 作为变量名,因为它是 python 中的关键字。

    import json
    a={}
    a["audio"]=[{"fs":"8000", "duration": "240"}]
    a1={"audio":a["audio"]}
    a["ref"]= [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]
    a2={"ref":a["ref"]}
    a={"audio":a["audio"], "ref":a["ref"]}
    with open("a.json", 'w') as fout:
        json.dump(a, fout)
    

    【讨论】:

    • 我的输出如下:{"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}], "audio": [{"fs": "8000", "duration": "240"}]}。格式正确,但“ref”和“audio”字典改变了它们的位置。你知道为什么吗?
    • 可以分享代码吗?还是和我发布的完全一样?
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2019-05-16
    • 2023-03-07
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多