函數(shù)式編程
2021-06-03 13:49:11
#Inputdict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250"}}dict_2 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.252"}}#Mapper can be modified as requiredmapper = {"10.10.210.250":"black","192.168.2.1":"black"} 我得到一個循環(huán)的每個字典,在每次迭代中,我需要根據(jù)之間的匹配所要檢查的映射器一個字典并附加標志dict_1.orig_h和mapper.10.10.210.250。我可以靈活地定義映射器,但我需要。所以想要的結(jié)果是:dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250", "class":"black"}}dict_2 將保持不變,因為映射器中沒有匹配的值。這有點像我想要的,但只有當orig_h它是intimport collectionsresult = collections.defaultdict(dict)for d in dict_1: result[d[int('orig_h')]].update(d)for d in mapper: result[d[int('orig_h')]].update(d)
3 回答

慕神8447489
TA貢獻1780條經(jīng)驗 獲得超1個贊
沒有太多解釋要做;如果 ip 在映射器字典中(如果mapper有一個鍵就是那個 ip),那么將所需的屬性設(shè)置dict為mapper字典中鍵的值('black'這里)。
def update_dict(dic, mapper):
ip = dic['conn']['orig_h']
if ip in mapper:
dic['conn']['class'] = mapper[ip]
完全按要求工作:
>>> update_dict(dict_1, mapper)
>>> dict_1
{'conn': {'ts': 15, 'uid': 'ABC', 'orig_h': '10.10.210.250', 'class': 'black'}}
>>> update_dict(dict_2, mapper)
>>> dict_2
{'conn': {'ts': 15, 'uid': 'ABC', 'orig_h': '10.10.210.252'}}

Smart貓小萌
TA貢獻1911條經(jīng)驗 獲得超7個贊
conn為簡單起見提取值:
conn_data = dict_1['conn']
conn_data['class'] = mapper[conn_data['orig_h']]
添加回答
舉報
0/150
提交
取消