[英]Find all keys which match multiple values in dictionary
I have a dictionary which looks like this.我有一本看起来像这样的字典。
dics = {'classes':[
{"class_number":'CIS41A', 'topic':'Python Programming', 'start_time':'8:30 AM', 'time_category':'Early Morning'},
{"class_number":'CIS41A', 'topic':'Java Programming', 'start_time':'11:30 AM', 'time_category':'Late Morning'} ,
{"class_number":'CIS41J', 'topic':'Python Programming', 'start_time':'8 PM', 'time_category':'Evening'},
{"class_number":'CIS41A', 'topic':'Linear Programming', 'start_time':'6 PM', 'time_category':'Evening'}
]
}
I want to yield class_number that have topics 'Python Programming','Java Programming' and Linear Programming我想产生class_number有主题“Python编程”,“Java编程”和线性规划
So output will be CIS41A所以输出将是CIS41A
You can do the following, using a collections.defaultdict
and set
intersection:您可以使用
collections.defaultdict
并set
交集来执行以下操作:
from collections import defaultdict
check = {'Java Programming', 'Python Programming', 'Linear Programming'}
def gen(dics):
topics = defaultdict(set)
for klass in dics['classes']:
topics[klass['class_number']].add(klass['topic'])
for klass_number in topics:
if topics[klass_number] & check == check:
yield klass_number
>>> list(gen(dics))
['CIS41A']
Is this what you wnat?这是你想要的吗?
from collections import defaultdict
dic = {
'classes': [
{"class_number": 'CIS41A', 'topic': 'Python Programming',
'start_time': '8:30 AM', 'time_category': 'Early Morning'},
{"class_number": 'CIS41A', 'topic': 'Java Programming',
'start_time': '11:30 AM', 'time_category': 'Late Morning'},
{"class_number": 'CIS41J', 'topic': 'Python Programming',
'start_time': '8 PM', 'time_category': 'Evening'},
{"class_number": 'CIS41A', 'topic': 'Linear Programming',
'start_time': '6 PM', 'time_category': 'Evening'},
{"class_number": 'CIS41A', 'topic': 'Fourth Topic',
'start_time': '9 PM', 'time_category': 'Evening'},
]
}
def gen(mandatory_topics: set):
topic_dict = defaultdict(set)
passed_classes = set()
for class_ in dic['classes']:
class_num = class_['class_number']
topic_dict[class_num].add(class_['topic'])
if topic_dict[class_num] >= mandatory_topics and class_num not in passed_classes:
passed_classes.add(class_num)
yield class_num
topics = {'Python Programming', 'Java Programming', 'Linear Programming'}
for item in gen(topics):
print(item)
output:输出:
CIS41A
I add 5th data for testing corner case.我添加了第 5 个数据来测试极端情况。
I need to pass the topic as individual arguments (like *args) not as a lists or sets.
我需要将主题作为单独的参数(如 *args)而不是列表或集合传递。 How can I change this code according?
我该如何更改此代码?
Change parameter and add code converting its type.更改参数并添加转换其类型的代码。
def gen(*mandatory_topics: str):
mandatory_topics = set(mandatory_topics)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.