加入由单独函数返回的字典,并将连接字典作为值分配到另一个字典中

时间:2017-09-23 03:31:10

标签: python function dictionary

我有3个函数,每个函数都返回一个字典。字典如下所示。我想将3个词典连成1个巨型字典。然后将此字典作为值传递,并为其指定一个名为“结果”的键。

get_energy()返回:

{'能源':{'largest_gainer':{'股权':'麦克德莫特国际','改变':'5.31%'},'largest_loser':{'股权':'比尔巴雷特公司','改变':' - 13.18%'},'更改':' - 1.48%'}}

get_materials()返回:

{'Basic Materials':{'largest_gainer':{'股权':'Gold Fields Limited(ADR)','变更':'3.22%'},'largest_loser':{'股权':'Jaguar Mining Inc(美国)','更改':' - 5.85%'},'更改':' - 0.35%'}}

get_industrials()返回:

{'industrials':{'largest_gainer':{'股权':'LML支付系统公司','变更':'633.43%'},'largest_loser':{'股权':'芝加哥大桥& ; Iron Co','change':' - 12.07%'},'change':' - 0.46%'}}

最终字典应如下所示:

{result:{'Energy': {'biggest_gainer': {'equity': 'McDermott International', 'change': '5.31%'}, 'biggest_loser': {'equity': 'Bill Barrett Corporation', 'change': '-13.18%'}, 'change': '-1.48%'}},
{'Basic Materials': {'biggest_gainer': {'equity': 'Gold Fields Limited (ADR)', 'change': '3.22%'}, 'biggest_loser': {'equity': 'Jaguar Mining Inc (USA)', 'change': '-5.85%'}, 'change': '-0.35%'}},
{'industrials': {'biggest_gainer': {'equity': 'LML Payment Systems, Inc.', 'change': '633.43%'}, 'biggest_loser': {'equity': 'Chicago Bridge & Iron Co', 'change': '-12.07%'}, 'change': '-0.46%'}}}

1 个答案:

答案 0 :(得分:2)

您可以将三个较小的词典解压缩为一个大词典。

result = {**get_energy(), **get_materials(), **get_industrials()}

相当于:

{
    "Energy": {
        "biggest_gainer": {
            "equity": "McDermott International",
            "change": "5.31%"
        },
        "biggest_loser": {
            "equity": "Bill Barrett Corporation",
            "change": "-13.18%"
        },
        "change": "-1.48%"
    },
    "Basic Materials": {
        "biggest_gainer": {
            "equity": "Gold Fields Limited (ADR)",
            "change": "3.22%"
        },
        "biggest_loser": {
            "equity": "Jaguar Mining Inc (USA)",
            "change": "-5.85%"
        },
        "change": "-0.35%"
    },
    "industrials": {
        "biggest_gainer": {
            "equity": "LML Payment Systems, Inc.",
            "change": "633.43%"
        },
        "biggest_loser": {
            "equity": "Chicago Bridge & Iron Co",
            "change": "-12.07%"
        },
        "change": "-0.46%"
    }
}