簡體   English   中英

在多個 Python 字典中映射值

[英]Mapping Values in multiple Python dicts

假設我有 2 個“空”字典:

keys_in = ["in1","in2"]
dict2 ={key: None for key in keys_in}
keys_out = ["out1","out2"]
dict3 ={key: None for key in keys_out}

我想將一個值從一個字典“映射”到另一個:

dict3["out1"] = dict2["in1"]

因此,如果設置了dict2["in1"]的值,我會在dict3["out1"]中得到相同的值

這可能嗎? 試過這個,值沒有改變:

keys_in = ["in1","in2"]
dict2 ={key: None for key in keys_in}
keys_out = ["out1","out2"]
dict3 ={key: None for key in keys_out}

dict3["out1"] = dict2["in1"]
dict2["in1"]  = 4

print(dict3["out1"]) #keeps being None
print(dict2["in1"]) # this of course  is 4

我在考慮 C++ 指針時產生了這個想法,但我不確定我的方向是否正確:s

不,這不是 Python 中賦值的工作方式。 請觀看內容或閱讀內容。 tl; dr:名稱被獨立重新分配

沒有任何進一步的上下文,您可以創建一個可變對象並在兩個 dicts 的值中使用它。 我從來沒有見過這樣的用例,我們可能在這里處理一個XY 問題,但一個例子可能是有教育意義的。

class MutableValue:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return repr(self.value)
    

演示:

>>> dict1 = {'in1': MutableValue(4)}
>>> dict2 = {'out1': dict1['in1']}
>>> dict1
{'in1': 4}
>>> dict2
{'out1': 4}
>>> dict1['in1'].value = 5
>>> dict1
{'in1': 5}
>>> dict2
{'out1': 5}

只是為了好玩,我們可以更進一步:

from collections import UserDict

class MutableValueDict(UserDict):
    def __setitem__(self, key, item):
        if key in self:
            self[key].value = item
        else:
            super().__setitem__(key, MutableValue(item))  

演示:

>>> dict1 = MutableValueDict({'in1': 4})
>>> dict2 = MutableValueDict({'out1': dict1['in1']})
>>> dict1
{'in1': 4}
>>> dict2
{'out1': 4}
>>> dict1['in1'] = 5 # no need to access .value
>>> dict1
{'in1': 5}
>>> dict2
{'out1': 5}

達到類似結果的一個棘手方法是為依賴字典dict3的每個值設置一個可調用函數,該函數可以訪問存儲在原始字典dict2中的值。 作為訪問dict3中的值的缺點,應該完成一個空調用,即dict3['out1']()

自然假設:兩個字典都有相同數量的項目(和正確的順序)。

# default initialisation
keys_in = ["in1","in2"]
dict2 = dict.fromkeys(keys_in, None)

# create a dictionary with callable values
keys_out = ["out1","out2"]
dict3 = {k3: lambda: dict2[k2] for k2, k3 in zip(keys_in, keys_out)}

# check content
print(dict3['out1']())

# add content to first dict
dict2['in1'] = 'dict2 -> in1'
dict2['in2'] = 'dict2 -> in2'

# check the updates
print(dict3['out1']())
#'dict2 -> in1'
print(dict3['out2']())
#'dict2 -> in2'

這是一種訪問dict3值的函數式編程方式,只是為了強調它的所有值都是可調用的:

from operator import methodcaller

vs = list(map(methodcaller('__call__'), dict3.values()))
print(vs)

暫無
暫無

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

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