#Input
dict_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 required
mapper = {"10.10.210.250":"black","192.168.2.1":"black"}
我循环获取每个字典,在每次迭代中,我需要根据映射器检查字典并根据dict_1.orig_h
和mapper.10.10.210.250
之间的匹配附加一个标志。我可以根据需要灵活地定义映射器。
因此,期望的结果将是:
dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250", "class":"black"}}
dict_2将保持不变,因为映射器中没有匹配的值。
这是我想要的,但只有当orig_h
是int
时才有效
import collections
result = 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)
没有太多的解释要做; 如果 ip 在映射器字典中(如果mapper
有一个键,那就是该 IP(,则将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'}}
为简单起见,提取conn
值:
conn_data = dict_1['conn']
conn_data['class'] = mapper[conn_data['orig_h']]
一个两行,提取类和字典,如果'orig_h'
在mapper
字典的键中,如果它id,保留它,否则不要保留它,然后在列表推导中创建一个新的字典理解,以'class'
添加到字典的'conn'
键的字典中。
l=[(i,mapper[i['conn']['orig_h']]) for i in (dict_1,dict_2) if i['conn']['orig_h'] in mapper]
print([{'conn':dict(a['conn'],**{'class':b})} for a,b in l])
顺便说一句,这个答案会自动选择字典