如何使用其他字典中的值建立 Python 字典?
可以透過將另一個字典合併到第一個字典中來完成此操作。在 Python 3.5+ 中,可以使用 ** 運算子來解包字典並使用以下語法合併多個字典 −
語法
a = {'foo': 125} b = {'bar': "hello"} c = {**a, **b} print(c)
輸出
這將給出以下輸出 −
{'foo': 125, 'bar': 'hello'}
以前的版本不支援此操作。不過,你可以用以下類似的語法替換它 −
語法
a = {'foo': 125} b = {'bar': "hello"} c = dict(a, **b) print(c)
輸出
這將給出以下輸出 −
{'foo': 125, 'bar': 'hello'}
還可以使用 copy 和 update 函式來合併字典。
示例
def merge_dicts(x, y): z = x.copy() # start with x's keys and values z.update(y) # modify z with y's keys and values return z a = {'foo': 125} b = {'bar': "hello"} c = merge_dicts(a, b) print(c)
輸出
這將給出以下輸出 −
{'foo': 125, 'bar': 'hello'}
廣告