从词典中删除重复 [英] Removing Duplicates From Dictionary
问题描述
{112762853378:
{'dst':['10 .121.4.136'],
'src':['1.2.3.4'],
'alias':['www.example。 com']
},
112762853385:
{'dst':['10 .121.4.136'],
'src':['1.2.3.4'],
'alias':['www.example.com']
},
112760496444:
{'dst':['10 .121.4.136'],
'src ':['1.2.3.4']
},
112760496502:
{'dst':['10 .122.195.34'],
'src':['4.3。 2.1']
},
112765083670:...
}
字典键将永远是独一无二的Dst,src和别名可以是重复的。所有记录将始终具有dst和src,但并不是每个记录必须具有在第三个记录中看到的别名。
在前两个记录的样本数据中将被删除(对我而言无关紧要)。第三个记录将被认为是唯一的,因为尽管dst和src是相同的,但它缺少别名。
我的目标是删除dst,src和别名的所有记录全部重复 - 无论密钥如何。
这个新秀如何实现?
另外,我对Python的有限理解将数据结构解释为具有字典中存储的字典的字典... dict的一个例子,这是正确的吗?
如果该值还没有在结果字典中,那么您可以通过字典中的每个项目(键值对)并将其添加到结果字典中。
input_raw = {112762853378:
{'dst':['10 .121.4.136'],
'src':['1.2.3.4'],
'alias':['www.example.com']
},
112762853385:
{'dst' ['10 .121.4.136'],
'src':['1.2.3.4'],
'alias':['www.example.com']
},
112760496444:
{'dst':['10 .121.4.136'],
'src':['1.2.3.4']
},
112760496502:
{'dst':['10 .122.195.34'],
'src':['4.3.2.1']
}
}
result =
为key,input_raw.items()中的值:
如果值不在result.values()中:
result [key] = value
打印结果
I have the following Python 2.7 dictionary data structure (I do not control source data - comes from another system as is):
{112762853378: {'dst': ['10.121.4.136'], 'src': ['1.2.3.4'], 'alias': ['www.example.com'] }, 112762853385: {'dst': ['10.121.4.136'], 'src': ['1.2.3.4'], 'alias': ['www.example.com'] }, 112760496444: {'dst': ['10.121.4.136'], 'src': ['1.2.3.4'] }, 112760496502: {'dst': ['10.122.195.34'], 'src': ['4.3.2.1'] }, 112765083670: ... }
The dictionary keys will always be unique. Dst, src, and alias can be duplicates. All records will always have a dst and src but not every record will necessarily have an alias as seen in the third record.
In the sample data either of the first two records would be removed (doesn't matter to me which one). The third record would be considered unique since although dst and src are the same it is missing alias.
My goal is to remove all records where the dst, src, and alias have all been duplicated - regardless of the key.
How does this rookie accomplish this?
Also, my limited understanding of Python interprets the data structure as a dictionary with the values stored in dictionaries... a dict of dicts, is this correct?
You could go though each of the items (the key value pair) in the dictionary and add them into a result dictionary if the value was not already in the result dictionary.
input_raw = {112762853378:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4'],
'alias': ['www.example.com']
},
112762853385:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4'],
'alias': ['www.example.com']
},
112760496444:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4']
},
112760496502:
{'dst': ['10.122.195.34'],
'src': ['4.3.2.1']
}
}
result = {}
for key,value in input_raw.items():
if value not in result.values():
result[key] = value
print result
这篇关于从词典中删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!