我正在尝试从字典中删除一个元素,但只有在满足条件时才能执行。
例如:
dd = {'11': [{'xx': 259, 'yy': 1, 'channels': 55}, {'xx': 260, 'yy': 2, 'channels': 35}], '22': [{'xx': 259, 'yy': 1, 'channels': 40}, {'xx': 303, 'yy': 2, 'channels': 30}]}
场景:
channels = 60
上述嵌套字典中有两个键为
xx = 259
的元素,我希望只保留离channels = 60
值更接近的一个元素。期望输出:
dd = {'11': [{'xx': 259, 'yy': 1, 'channels': 55}, {'xx': 260, 'yy': 2, 'channels': 35}], '22': [{'xx': 303, 'yy': 2, 'channels': 30}]}
我已经尝试过以下方法:
channels = 60
for key, values in dd.items():
key = str(key)
if key in dd:
for elem in dd[key]:
if elem['xx'] == 259:
print(elem)
# some logic here to check the closest value to channels and remove the furthest one
这将输出:
{'xx': 259, 'yy': 1, 'channels': 55}
{'xx': 259, 'yy': 1, 'channels': 40}
更新方法:
channels = 60
xList = []
for key, values in dd.items():
key = str(key)
if key in dd:
for elem in dd[key]:
if elem['xx'] == 259:
xList.append(elem['channels'])
result =min(xList, key=lambda x: abs(x - 60))
# find and remove elem from dict
for key, values in dd.items():
key = str(key)
if key in dd:
for elem in dd[key]:
if elem['xx'] == 259:
if elem['channels'] == result:
pass
else:
print("delete this elem: ", elem)
dd[key].remove(elem)
print(dd)
输出:
{'11': [{'xx': 259, 'yy': 1, 'channels': 55}, {'xx': 260, 'yy': 2, 'channels': 35}], '22': [{'xx': 303, 'yy': 2, 'channels': 30}]}
我达到了最终目标,但我觉得这可以进一步改善。需要帮忙吗?