如何透過另一個字典中的值建立 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'}

更新於:17-Jun-2020

2 千次觀看

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告