我正在做一个Python项目,它需要在字典中查找集合值。你知道吗
我有两本字典,都以ID为键。一个字典的值是名称,另一个字典的值是电子邮件。你知道吗
例如:
Names Dictionary:
{'cbp750': 'Crystle Purifoy', 'mis918': 'Marquita See', 'bmb865': 'Bok
Bobbitt', 'dch273': 'Danny Halverson', 'etf890': 'Elvia Fortin', 'nve360':
'Nakisha Ehrmann'}
Emails Dictionary:
{'cbp750': 'c.purifoy@utexas.edu', 'mis918': 'm.see@utexas.edu', 'bmb865':
'b.bobbitt@utexas.edu', 'dch273': 'd.halverson@utexas.edu', 'etf890':
'e.fortin@utexas.edu', 'nve360':'n.ehrmann@utexas.edu'}
如果我有一组值,例如:{'mis918', 'etf890', 'nve360'}
,那么如何在字典中查找这些设置值以返回名称和格式为name(email)的email,以便查找mis918
将返回Marquita See (M.See@utexas.edu)
?你知道吗
我目前使用for循环的尝试失败了,所以我不知道应该从哪里开始。非常感谢你的帮助。你知道吗
为了从
dict
访问项目,可以将key
作为dict[key]
传递以访问其值。在您的例子中,key是set
中的项。迭代set
,并使用item
作为键,从email_dict
和name_dict
获取值。你知道吗注意:如果
set
中的项目可能不是dict
中的key
,请使用dict.get(key, '')
。它将返回值作为未知键的''
空字符串。例如:下面是您的问题的示例代码(假设
item
中的所有set
都存在于您的dict
):其中
email_dict
和name_dict
是所讨论的dict,即:我不确定这是您要查找的内容,但您可以通过传入键来访问字典值:
简单的一行回答是:
相关问题 更多 >
编程相关推荐