Я не знаю, что означает document
в этом контексте, поэтому этот ответ может быть ошибочным.
Введите:
mylist = [{('love', 'sex'): '6.77',
('tiger', 'cat'): '7.35',
('tiger', 'tiger'): '10.00',
('book', 'paper'): '7.46',
('computer', 'keyboard'): '7.62',
('computer', 'internet'): '7.58',
('computer', 'car'): '7.58',
('computer', 'plane'): '7.58',
('computer', 'train'): '7.58',
('computer', 'television'): '7.58',
('computer', 'radio'): '7.58',
('computer', 'tiger'): '7.58',
('computer', 'test1'): '7.58',
('computer', 'test2'): '7.58',
('tiger', 'tz1'): '7.58',
('tiger', 'tz2'): '7.58',
('tiger', 'tz3'): '7.58',
('tiger', 'tz4'): '7.58',
('tiger', 'tz5'): '7.58',
('tiger', 'tz6'): '7.58',
('tiger', 'tz7'): '7.58',
('tiger', 'tz8'): '7.58',
('plane', 'car'): '5.77',
('train', 'car'): '6.31',
('telephone', 'communication'): '7.50',
('television', 'radio'): '6.77',
('media', 'radio'): '7.42',
('drug', 'abuse'): '6.85'}]
Решение:
Обратите внимание, что решение должно перебирать словарь дважды (хотя второй цикл обычно будет проходить только по части словаря). Я также рассматриваю каждый словарь в списке как отдельную вещь, поэтому вам может понадобиться переместить некоторые из них.
# This will be the keys we want to remove
removable_keys = set()
# This will be the number of times we see a key part (left or right)
occurences = dict()
# For each dictionary in our list
for dic in mylist:
# For each key in that dictionary
for key in dic:
# If the key is not in alphabetical order
if list(key) != sorted(list(key)):
# We will remove that key
removable_keys.add(key)
# Else this is a valid key
else:
# Increment the number of times we have seen this key
left, right = key
occurences[left] = 1 if left not in occurences else occurences[left] + 1
occurences[right] = 1 if right not in occurences else occurences[right] + 1
# No we need to look for keys that had less than 8 occurences.
for key in dic.keys() - removable_keys:
left, right = key
if occurences[left] < 8 or occurences[right] < 8:
removable_keys.add(key)
# Finally remove all those keys from our dict
for key in removable_keys:
del dic[key]
print(dic)
Выход:
{('tiger', 'tiger'): '10.00', ('computer', 'tiger'): '7.58'}