连接集合和字典

2024-09-29 21:40:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个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循环的尝试失败了,所以我不知道应该从哪里开始。非常感谢你的帮助。你知道吗


Tags: 项目名称dictionary字典emaileduseeutexas
3条回答

为了从dict访问项目,可以将key作为dict[key]传递以访问其值。在您的例子中,key是set中的项。迭代set,并使用item作为键,从email_dictname_dict获取值。你知道吗

注意:如果set中的项目可能不是dict中的key,请使用dict.get(key, '')。它将返回值作为未知键的''空字符串。例如:

>>> my_dict = {'a': 2}
>>> my_dict.get('a', '')  # Returns value as 'a' is key in 'my_dict'
2 
>>> my_dict.get('b', '')  # Return empty string as 'b' is not key in 'my_dict'
''

下面是您的问题的示例代码(假设item中的所有set都存在于您的dict):

my_set = {'mis918', 'etf890', 'nve360'}
for item in my_set:
    print('Set Value: ', item, ' ; Email: ', email_dict[item], ' ; Name: ', name_dict[item])

# Output of above code 
Set Value:  etf890  ; Email:  e.fortin@utexas.edu  ; Name:  Elvia Fortin
Set Value:  mis918  ; Email:  m.see@utexas.edu  ; Name:  Marquita See
Set Value:  nve360  ; Email:  n.ehrmann@utexas.edu  ; Name:  Nakisha Ehrmann

其中email_dictname_dict是所讨论的dict,即:

name_dict = {
        'cbp750': 'Crystle Purifoy', 
        'mis918': 'Marquita See', 
        'bmb865': 'BokBobbitt', 
        'dch273': 'Danny Halverson', 
        'etf890': 'Elvia Fortin', 
        'nve360': 'Nakisha Ehrmann'
    }

email_dict = {
        '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'
   }

我不确定这是您要查找的内容,但您可以通过传入键来访问字典值:

names = {
    'cbp750': 'Crystle Purifoy',
    'mis918': 'Marquita See',
    'bmb865': 'Bok Bobbitt',
    'dch273': 'Danny Halverson',
    'etf890': 'Elvia Fortin',
    'nve360': 'Nakisha Ehrmann'
}

emails = {
    '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'
}


set_of_ids =  {'mis918', 'etf890', 'nve360'}

for _id in set_of_ids:
    if _id in names and _id in emails:
        print('{} ({})'.format(names[_id], emails[_id]))

简单的一行回答是:

# names -> name dictionary, emails -> email dictionary, idSet -> contains ids to be searched.

['{} ({})'.format(names[idx], emails[idx]) for idx in idSet if idx in names and idx in emails]

相关问题 更多 >

    热门问题